元素ID未被识别并且不是触发功能 [英] Element IDs are not being recognised and are not triggering function
问题描述
在选择特定的字体样式时,我正在为用户创建简单的选择选项。如果他们点击字体 div
,那么 div
的背景应该改变颜色。
我遇到的问题是,第一个字体 div
在更改颜色方面可以完美地工作,而另一种字体 div
不遵守。
HTML
< div class =fonts>
< div id =fontclass =minecraft-evenings>
Hello
< p> Minecraft Evenings< / p>
< / div>
< div id =fontclass =minecrafter>
Hello
< p> Minecrafter 3< / p>
< / div>
< div id =fontclass =volter>
Hello
< p> Volter< / p>
< / div>
< / div>
JavaScript / JQuery
($($)$($)$($)$($)$($) .css(background-color,#f1f1f1);
(背景颜色,#000);
$('#font' });
});
问题: br>
ID是唯一的标识符。如果要标识多个元素,应该使用类。因此,当您使用 $(#font)
选择ID时,jQuery(使用本机javascript的 getElementById
)将只返回具有该ID的第一个元素。这是因为如果DOM是有效的,它不应再找到该ID的实例,这将是浪费继续查找的处理。
A解决方案:
从您的 div
中删除字体
使用类,如 class =font
。由于您已经识别了一些类,因此可以使用由空格分隔的多个类,例如: class =font minecrafter
。执行此操作后,您可以使用此选择器使用字体类型选择元素:
$(。font)
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 div
s do not follow suit.
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");
});
});
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 div
s 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")
这篇关于元素ID未被识别并且不是触发功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!