Javascript 遍历元素并添加索引号
为什么此代码在被单击时会向所有h2元素添加Javascript 遍历元素并添加索引号,javascript,jquery,Javascript,Jquery,为什么此代码在被单击时会向所有h2元素添加class=hello5?有4个h2元素 for (i=0; i < $('h2').length; i++) { $('#' + i).click(function(index) { $(this).addClass('hello' + i) }) }; 我必须添加另一个循环吗?我很困惑。谢谢。主要问题是您希望处理程序的参数作为索引,但它不是,而是eventObject 您最好像这样使用.each()函数: $("h2").ea
class=hello5
?有4个h2元素
for (i=0; i < $('h2').length; i++) {
$('#' + i).click(function(index) {
$(this).addClass('hello' + i)
})
};
我必须添加另一个循环吗?我很困惑。谢谢。主要问题是您希望处理程序的参数作为索引,但它不是,而是eventObject 您最好像这样使用.each()函数:
$("h2").each(function(index, item){
$(item).click(function(e){
e.preventDefault();
$(this).addClass("hello" + index);
})
})
主要问题是您希望处理程序的参数作为索引,但它不是,而是eventObject 您最好像这样使用.each()函数:
$("h2").each(function(index, item){
$(item).click(function(e){
e.preventDefault();
$(this).addClass("hello" + index);
})
})
回调中的
i
与递增的i
相同。在触发这些回调函数时,i
的值将是8
,因此所有回调都将添加相同的类
通常避免在循环中创建事件处理程序。一次选择这些元素并向所有元素添加单个事件处理程序要容易得多:
$('h2').click(function() {
$(this).addClass('hello' + this.id);
});
i
在您的回调中与您正在递增的i
相同。在触发这些回调函数时,i
的值将是8
,因此所有回调都将添加相同的类
通常避免在循环中创建事件处理程序。一次选择这些元素并向所有元素添加单个事件处理程序要容易得多:
$('h2').click(function() {
$(this).addClass('hello' + this.id);
});
我编辑了您的html代码片段:
<h2 id="id0">0</h2>
<h2 id="id1">1</h2>
<h2 id="id2">2</h2>
<h2 id="id3">3</h2>
我编辑了您的html代码片段:
<h2 id="id0">0</h2>
<h2 id="id1">1</h2>
<h2 id="id2">2</h2>
<h2 id="id3">3</h2>
因为当时的click事件是fire。变量
i
是finish循环,它得到值4。解决方案是使用必须获得h2
元素的索引并分配给类。我有一点变化:
$().ready(function () {
for (i = 0; i < $('h2').length; i++) {
$('#' + i).click(function (index) {
$(this).addClass('hello' +$("h2").index( $(this)))
})
};
})
$().ready(函数(){
对于(i=0;i<$('h2')。长度;i++){
$('#'+i).单击(函数(索引){
$(this).addClass('hello'+$('h2”).index($(this)))
})
};
})
因为当时的click事件是fire。变量
i
是finish循环,它得到值4。解决方案是使用必须获得h2
元素的索引并分配给类。我有一点变化:
$().ready(function () {
for (i = 0; i < $('h2').length; i++) {
$('#' + i).click(function (index) {
$(this).addClass('hello' +$("h2").index( $(this)))
})
};
})
$().ready(函数(){
对于(i=0;i<$('h2')。长度;i++){
$('#'+i).单击(函数(索引){
$(this).addClass('hello'+$('h2”).index($(this)))
})
};
})
您只需执行
$('h2').addClass(函数(i){return'hello'+i;})代码>,但在单击元素时两者都不会触发。谢谢您的评论。我错过了OP需要通过单击添加类的内容。我不知道我可以用这种方式使用addClass,你可以只做$('h2').addClass(函数(I){return'hello'+I;})代码>,但在单击元素时两者都不会触发。谢谢您的评论。我错过了OP需要通过单击添加类的内容。我不知道我可以这样使用addClass。元素id不能以数值开头。@ravisoni:可以在HTML5中使用。@aaa检查答案和工作小提琴元素id不能以数值开头。@ravisoni:可以在HTML5中使用。@aaa检查答案和工作小提琴