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
281 views
in Technique[技术] by (71.8m points)

javascript - Element IDs are not being recognised and are not triggering function

I'm trying to create simple selection option for users when selecting a particular font style. If they click on a font div, the background of that div should change color.

The problem I'm having is that the first font div works perfectly in changing color - however the other font divs do not follow suit.

JSFiddle

HTML

<div class="fonts">
  <div id="font" class="minecraft-evenings">
      Hello
      <p>Minecraft Evenings</p>
  </div>
  <div id="font" class="minecrafter">
      Hello
      <p>Minecrafter 3</p>
  </div>
  <div id="font" class="volter">
      Hello
      <p>Volter</p>
  </div>
</div>

JavaScript/JQuery

$(document).ready(function() {
    $('#font').click(function() {
        $(this).css("background-color", "#000");
        $('#font').not(this).css("background-color", "#f1f1f1");
    });
});
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The problem:
ID's are meant to be unique identifiers. You should be using classes if you want to identify multiple elements. For this reason, when you select by ID with $("#font"), jQuery (which uses native javascript's getElementById) will only return the first element it comes across that has that ID. This is because if the DOM is valid, it shouldn't find anymore instances of that ID and it would be a waste of processing to continue looking.

A solution:
Remove the font ID's from your divs and replace them with a class instead, like class="font". Since you already have some classes identified, you can use multiple classes separated by spaces, like: class="font minecrafter". After doing this, you will be able to select your elements with the font class using this selector: $(".font")


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

...