将jQuery单击处理程序添加到多个元素? [英] Add jQuery click handler to multiple elements?
本文介绍了将jQuery单击处理程序添加到多个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在我的jQuery中有一个 for
循环。
I need to have a for
loop inside my jQuery.
示例:
for(i=0;i<counter;i++)
{
$("div"+i+"").click(function(){//some code});
}
我该如何做到这一点?
此代码由OP发布,对其中一个答案发表评论:
This code was posted by the OP in a comment to one of the answers:
$("#displayPanel div").click(function (){ alert($(this).attr("id")); }
<div id="displayPanel" class="displayPanel">
<div id="heading"> Display Panel </div> <br/>
<div id="save" class="saveClass"></div> <br/>
<div id="field1" class="my">
<label id="labelstr1">Untitled1</label>
<input id="inputstr1" type="text"/>
</div>
<div id="field2" class="my">
<label id="labelstr2">Untitled1</label>
<input id="inputstr2" type="text"/>
</div>
</div>
警告显示前两个 div
的ID,而不是 field1
和 field2
。
The alert is showing me the id for the first two div
s and not for the field1
and field2
.
Field1
和 Field2
div
s即时创建。
推荐答案
你可以把div放到公共类
You can put the divs with a common class
<div id="d1" class="your_css_class your_control_class">
<div id="d2" class="your_css_class your_control_class">
<div id="d3" class="your_css_class your_control_class">
<div id="d4" class="your_css_class your_control_class">
<div id="d5" class="your_css_class your_control_class">
$(".your_control_class").click(function(){
var div_id=$(this).attr("id"); // gives you the ID of the clicked div
if(div_id==="d1") functionForDiv1();
else if(div_id==="d2") functionForDiv2();
...
});
编辑:
如果你拥有一切在那个大div里面你可以做:
If you have everything inside that big div then you can do:
$("#displayPanel > div").click(function(){
...
这篇关于将jQuery单击处理程序添加到多个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文