2013-03-15 55 views
1

我有一個類的TextBox,並在按鈕單擊我追加同一類的另一個元素。頁面加載後生成的控件的jquery事件

我該如何讓新TextBox的行爲像其他類一樣?

例子:http://jsfiddle.net/GCQKE/

HTML:

<div class="container"> 
    <input id="textbox1" type="text" class="textbox" /> 
    <input id="textbox2" type="text" class="textbox" /> 
    <input id="textbox4" type="text" class="textbox" /> 
</div> 
<input type="button" class="append" value="Append new TextBox" /> 

JQUERY

$(".append").click(function (e) { 
    $(".container").append("<input id='textbox3' type='text' class='textbox' />"); 
}); 


$(".textbox").click(function (e) { 
    alert($(e.target).attr("id")); 
}); 

當我點擊所有的文本框,我得到的警報,exept的按鈕點擊所產生的一個。任何建議?

回答

1

DEMO (jsfiddle updated)

你應該使用正確的語法爲.on()爲未來的元素通過爲此結合該事件存在的代碼運行時父母並給它您實際上希望事件綁定到的孩子的選擇器。

$('.container').on('click', '.textbox', function() { 
    //alert($(this).attr("id")); 
    console.log(this.id); 
}); 
1

.click(...)只綁定到對頁面加載該類元素,

如果你想綁定到一個類的所有元素的功能現在或將來

(出現在頁面加載或動態插入),使用jQuery的委託......

http://api.jquery.com/delegate/

更換

$(".textbox").click(function (e) { 
    alert($(e.target).attr("id")); 
}); 

$('.container').delegate('.textbox', 'click', function(e){ 
    alert($(e.target).attr("id")); 
}); 
相關問題