Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

jQuery: dealing with a space in the id attribute

I have an element with id="A B". The following code fails:

<input type="text" id="A B">
<script>$("#A B").click(function(){alert();});</script>

The following code does not fail:

<input type="text" id="AB">
<script>$("#AB").click(function(){alert();});</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

While it’s technically invalid to have a space in an ID attribute value in HTML (see @karim79’s answer), you can actually select it using jQuery.

See http://mothereffingcssescapes.com/#A%20B:

<script>
  // document.getElementById or similar
  document.getElementById('A B');
  // document.querySelector or similar
  $('#A\ B');
</script>

jQuery uses a Selectors API-like syntax, so you could use $('#A\ B'); to select the element with id="A B".

To target the element in CSS, you could escape it like this:

<style>
  #A B {
    background: hotpink;
  }
</style>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...