将jQuery单击处理程序添加到多个元素?
我需要在我的jQuery中有一个for
循环。
例:
for(i=0;i<counter;i++) { $("div"+i+"").click(function(){//some code}); }
我怎么能做到这一点?
编辑:
此代码由OP发布,对其中一个答案发表评论:
$("#displayPanel div").click(function (){ alert($(this).attr("id")); } Display Panel
警报显示前两个div
的id,而不是field1
和field2
。
注意:
Field1
和Field2
div
是动态创建的。
您可以将div与公共类放在一起
$(".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里面的所有东西,那么你可以这样做:
$("#displayPanel > div").click(function(){ ...
循环似乎是不必要的,因为div的选择器将应用于所有div。
$("div").click(function(){ //this will apply to any div you click on the page //for example: $(this).css('color','red'); //change the color of the div clicked to red });
编辑 :由于您在编辑中提到动态创建了#field1和#field2,因此您需要使用.live()来绑定click事件,如下所示:
$("#displayPanel div").live('click', function(){ alert($(this).attr('id')); });
例如,您可以循环遍历所有div,如下所示:
$("div").each(function() { $(this).hide(); // this points to the current element });
是的,您可以在jQuery中使用for循环,但从您的问题看,您可能不需要它。 当你使用
$('div').click(function(). { ... });
您可以使用一个命令将该函数绑定为所有div的事件处理程序。 您还可以使用上下文 , 类名或其他属性来过滤应用事件处理程序的div。
如果你想为每个div执行不同的操作,最好在每个div上有一个唯一的ID,然后使用事件处理程序绑定
$('#divId').click(function() { ... });
假设html是
h c h c h c
您可以使用jquery以这种方式循环:例如,当您单击标题时,内容将被隐藏。
$(".module").each(function(index){ $("#header"+index).click(function(){ $("content"+index).hide() }); });
您可能想看一下jQuery.each(集合,回调(indexInArray,valueOfElement))函数http://api.jquery.com/jQuery.each/
这些div
有共同的父,属性还是其他什么? 按特定forms的ID匹配( divXYZ
在您的情况下为divXYZ
)可能不是最容易/最明显的事情。 Selectors的API文档有一个完整的列表,列出了您可以选择元素的不同方法。 选择最合适的选项,JQuery变得更加简化。
以下是使用公共父级选择div的示例:
$("#parent > div").click(function() { // some code });
并且为了选择具有公共属性的 div(如果它们没有共同的父项,则一个解决方案可以为它们分别提供cusotm属性):
$("div[fooAttribute]").click(function() { // some code });