Trying to figure this one out and I think I know the problem but I don't know how to fix it. When my page first loads I'm using a JSON file to provide some links on the page, using $.getJSON to create them and give them ID's, dynamically. My code for that is (this is just the bit I'm interested in for now, I of course close the function):
我试着解决这个问题,我想我知道这个问题,但我不知道如何解决它。当我的页面第一次加载时,我使用一个JSON文件在页面上提供一些链接,使用$。getJSON会创建它们并动态地给它们ID。我的代码是(这只是我现在感兴趣的部分,我当然关闭了函数):
$(function() {
$.getJSON("data.json", function(data) {
var navOutput = "";
for (var key in data.navigation) {
navOutput += '<li><a id="' + key + '">' + data.navigation[key] + '</a></li>'; // Create list items with ID 'key'
}
$("#mainNav").html(navOutput);
Everything loads fine on the page. Outside of the $.getJSON function I am trying to assign an event listener to one of those dynamically created ID's, as an example:
页面上的内容都很好。在美元之外。getJSON函数我试图为其中一个动态创建的ID分配一个事件监听器,例如:
$("#cast").click(function() {
alert("Testing");
}); //click function
This doesn't seem to work. There is probably a simple answer to this but I can't figure it out. If I assign an event handler to an ID on the page created in the HTML, it works, so it has something to do with these dynamic ID's. Any help would be appreciated.
这似乎行不通。可能有一个简单的答案,但我想不出来。如果我将事件处理程序分配给HTML中创建的页面上的ID,它会工作,因此它与这些动态ID有关。如有任何帮助,我们将不胜感激。
1 个解决方案
#1
10
Change
改变
$("#cast").click(function() {
alert("Testing");
});
to
来
$("body").on("click","#cast",function(e) {
alert("Testing");
});
You need to set handler with on
instead of click
. It's advancement to live()
. It'll allow you to attach handler to dynamically loaded elements. click
will attach only on dom ready ie while page is laoded initially.
您需要设置处理程序为on,而不是单击。生活的进步()。它允许您将处理程序附加到动态加载的元素。当页面初始化时,单击将只附加在dom准备好的ie上。
#1
10
Change
改变
$("#cast").click(function() {
alert("Testing");
});
to
来
$("body").on("click","#cast",function(e) {
alert("Testing");
});
You need to set handler with on
instead of click
. It's advancement to live()
. It'll allow you to attach handler to dynamically loaded elements. click
will attach only on dom ready ie while page is laoded initially.
您需要设置处理程序为on,而不是单击。生活的进步()。它允许您将处理程序附加到动态加载的元素。当页面初始化时,单击将只附加在dom准备好的ie上。