2012-04-16 75 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")