Jquery点击function不适用于动态元素
我正在使用$.each
为每个数组对象创建按钮。 我还尝试给每个按钮一个特定的id,所以我可以点击事件进行进一步编码,但现在我不知道为什么所有按钮都不起作用。 我错过了一些代码吗?
var questlist = [{ "startdate": "2015-01-08", "questitem": [ { "questid": "1", "gifttype": "stars", "quantity": 10, "questname": "One", "queststatus": "done" }, { "questid": "2", "gifttype": "stars", "quantity": 50, "questname": "Two", "queststatus": "ready" }, { "questid": "3", "gifttype": "stars", "quantity": 100, "questname": "Three", "queststatus": "complete" }, { "questid": "4", "gifttype": "stars", "quantity": 120, "questname": "Four", "queststatus": "done" }, { "questid": "5", "gifttype": "stars", "quantity": 220, "questname": "Five", "queststatus": "ready" }, ] }]; questitemlist(questlist); function questitemlist() { var callquest = "" + "" + ""; $("#call_quest").append(callquest); var questlistobj = questlist[0].questitem; $.each(questlistobj, function(i, obj) { if (obj.queststatus == "ready") { var questlist_item_button = ""; $("#questlist_item_button_go" + obj.questid).click(function() { alert("go"); }); console.log("#questlist_item_button_go" + obj.questid); } else if (obj.queststatus == "done") { var questlist_item_button = ""; $("#questlist_item_button_reward" + obj.questid).click(function() { alert("reward"); }); } else if (obj.queststatus == "complete") { var questlist_item_button = ""; } var questlist_item = "" + questlist_item_button + "" + "" + ""; $("#call_questitem").append(questlist_item); }); }
您可以在具有直接绑定的元素上调用click()
函数。 直接绑定将仅附加在DOM加载时存在的事件处理程序,即静态元素。
如果在加载DOM之后创建了元素,那么如果没有正确附加事件处理程序,则不会触发与它们关联的所有事件。
当你创建动态元素时意味着它们是在加载DOM之后创建的,并且在直接绑定时它们不存在,所以你不能直接调用click()
。
如果要在动态创建的元素上获得click
function,则可以使用on创建委派绑定 。 这可以通过向静态父元素添加.on
处理程序来实现。
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
改变这一行
$("#questlist_item_button_reward" + obj.questid).click(function() { alert("reward"); });
至
$("#call_questitem").on("click", "#questlist_item_button_reward" + obj.questid, function() { alert("reward"); });
并且也为go
按钮执行相同操作。
DEMO
您正在使用questlist_item_button
覆盖动态ID。
value='GO !'/>
那是因为您的DOM将在运行中创建。 所以你必须使用jQuery的委托:
在具有所选ID的文档上绑定点击事件:
$(document).on('click', '#questlist_item_button_go'+obj.questid, function(){ // your action here });
您必须使用.on()
函数为动态创建的元素附加事件。
例
$(document).on('click', '#DYNAMIC_ELEMENT_ID', function(){ // your action here });