[英]How to use ID selector after jQuery html()
嘗試理解為什么在多次單擊后沒有生成函數alert("hello")
這真是太棒了...有一些方法可以執行此功能嗎?
請注意,使用html()
進行更新后無法正常工作,該按鈕包含id“按”按鈕。
任何的想法? 請參閱: http : //jsbin.com/atuqu3
JavaScript的:
$(document).ready(function (){
$("#press").click(function() {
$("#relation-states").html('<select id="state" name="state"> <option value="Texas">Texas</option> </select><button id="press" type="button" title="" aria-haspopup="true" style="width: 175px;"><span>Select an item</span></button>');;
alert("hello");
});
});
HTML:
<div id="relation-states">
<select id="state" name="state">
<option value="New York">New York</option>
</select>
<button id="press" type="button" title="" aria-haspopup="true" style="width: 175px;"><span>Select an item</span></button>
</div>
您正在用id“relation-states”替換整個div
的內容,這也是刪除事件處理程序(因為刪除了附加處理程序的DOM節點)。 如果要將事件處理程序綁定到現在或將來遇到選擇器的所有元素,請查看live
:
$("#press").live("click", function() {
$("#relation-states").html('<select id="state" name="state"> <option value="Texas">Texas</option> </select><button id="press" type="button" title="" aria-haspopup="true" style="width: 175px;"><span>Select an item</span></button>');;
alert("hello");
});
或delegate
:
$("#relation-states").delegate("#press", "click", function() {
$("#relation-states").html('<select id="state" name="state"> <option value="Texas">Texas</option> </select><button id="press" type="button" title="" aria-haspopup="true" style="width: 175px;"><span>Select an item</span></button>');;
alert("hello");
}
使用.html()
,您將刪除該元素的所有子元素並將其替換為新元素。 這意味着附加到這些孩子的任何事件處理程序都會丟失。 你可以通過只替換你真正需要的東西來避免這種情況:
$('#state').html('<option value="Texas">Texas</option>');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.