Element IDs are not being recognised and are not triggering function

房东的猫 提交于 2019-12-26 08:25:50

问题


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");
    });
});

回答1:


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")



来源:https://stackoverflow.com/questions/18021584/element-ids-are-not-being-recognised-and-are-not-triggering-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!