javascript-jQuery click()事件不适用于附加的html标签
作者:互联网
在我的问题变得有意义之前,我需要解释几件事.在我的第一页上,我有一个主div,在其中使用jquery load()方法从另一页加载标记.我正在加载的html链接到脚本所在的.js页面. js页面是我处理主div内容的地方.
在我的js页面上,我遍历了从数据库中提取的变量数组,并将它们append()附加到主div.在for循环中,我将每一行包装在自己的div中,并包含一个定位标记.锚标记是我想要附加click()方法的对象,因此单击该函数后就可以调用它.我已经尝试过父母>子选择器等,但对于锚标记无效.我的代码:
//this is the query to my parse database
query.find({
success: function(results) {
for (i = 0; i < results.length; i++){
activity = results[i].get("activity");
scene = results[i].get("location");
neighborhood = results[i].get("neighborhood");
date = results[i].get("date");
details = results[i].get("details");
time = results[i].get("time");
search.push([activity, scene, neighborhood, date, details, time]);
for (i = 0; i < search.length; i++) {
//append each row of results to mainDiv inside of their own div with an anchor tag at the end of each row.
//when the anchor tag is clicked I want to call a function, but none of the selectors I've tried have worked.
$('#mainDiv').append("<div id='event'>" + search[i].join(' ') + "<a href='#' id='interested'>Interested?</a></div>");
}
};// closes for loop
},//closes success function
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
}); //closes find
解决方法:
我在这里找到了答案:
Newly appended div doesn’t inherit event handler in document ready
快捷方式事件处理程序(例如click(),mouseover()等)将仅应用于页面加载时可用于DOM的元素.动态添加元素时,必须将事件附加到静态父元素,并提供希望将事件委托给的过滤器,如下所示:
这是我的解决方案:
$("#mainDiv").on('click', '.interested', function(){
alert("working");
});
标签:javascript,jquery-selectors,parent-child,append 来源: https://codeday.me/bug/20191012/1897382.html