2012-04-16 72 views
0

我一个开发一个应用程序中,我使用jQuery的类选择

$("#plblAgreeProblem",".plblAgreeComment").live("click", function(){ 
     alert("bil"); 
} 

但类选择不工作。我的div class =“plblAgreeComment”正在动态创建,所以我使用.live()

请帮助我。

+0

什么不起作用? – Bergi 2012-04-16 19:21:43

+0

你能提供你的HTML吗? – 2012-04-16 19:22:42

+0

警报不叫 – Billz 2012-04-16 19:22:54

回答

0

如果你正在使用jQuery版本较新,且包括了 “对” 使用:

$(document).on("click", "#plblAgreeProblem, .plblAgreeComment" ,function(){ 
     alert("bil"); 
}); 

注意:如果可能的话,请尝试绑定比“文档”更接近的东西 - 例如标记的该部分的包装等,以便处理速度问题。

其他答案覆盖之前的版本

这里是它的工作示例包:http://jsfiddle.net/MarkSchultheiss/pP6nL/

+1

注意:我根据你的另一个问题做了一个疯狂的假设,那就是两个截然不同的选择器,而不是另一个。是不正确的,如果您发布标记,我们会改进。 – 2012-04-16 19:29:22

2

问题不是很清楚。对于选择器,请尝试使用以下内容。

$("#plblAgreeProblem, .plblAgreeComment").live("click", function(){ 
     alert("bil"); 
}); 

$(".plblAgreeComment").live("click", function(){ 
     alert("bil"); 
}); 
+2

[-1建议不要使用直播](http://jsperf.com/jquery-live-vs-delegate-vs-on)。 :P – PeeHaa 2012-04-16 19:23:37

+3

@RepWhoringPeeHaa。不好的电话,这是使用“活”的OP!请回复它! – gdoron 2012-04-16 19:24:14

+2

因为他没有列出他的版本,所以他可能会使用旧版本的jQuery。我会说你的判断很糟糕。 .on()仅适用于jQuery 1.7+ – 2012-04-16 19:24:34

1

首先,你应该知道,live在当前的jQuery版本过时,你应该使用on代替。

这就是说,你的选择$("#plblAgreeProblem",".plblAgreeComment"),将搜索元素与与plblAgreeCommentclass#plblAgreeProblemid的元素。它是你想写的选择器吗?

另一个说明,id必须是唯一的,这意味着页面中不能多于一个元素具有相同的id属性。

喔..你在live函数结束时忘了);

$("#plblAgreeProblem",".plblAgreeComment").live("click", function(){ 
     alert("bil"); 
}); 
+0

亲爱的它不工作:( – Billz 2012-04-16 19:32:46

+0

@ user1334569。你能给我你的HTML结构吗?是你要附加它的元素事件有'id' 'plblAgreeProblem',它存在于'plblAgreeComment'类的元素中??? ??? – gdoron 2012-04-16 19:48:44

0

如果与类“plblAgreeComment”你的元素在里面的节点“#plblAgreeProblem”尝试使用不同势选择而不是:

$("#plblAgreeProblem .plblAgreeComment")