我有一個問題。我試圖動態添加菜單元素到我的網頁。這個問題是我通過回調來處理頁面導航。通過我現在使用的代碼,只有數組的LAST元素才能正常工作。我不確定這是爲什麼,但我想在這裏得到一些幫助。我還提供了一個jsfiddle頁面,以便您可以看到發生了什麼。JQuery動態添加回調
代碼:https://jsfiddle.net/usz2nvqw/
HTML:
<div id='page_nav'>
<!-- Navigation Elements -->
</div>
JAVASCRIPT:
var pages = {
"home": {
"resource_name": "Home",
"name": "Home Page",
"header": "Featured"
},
"catalogue": {
"resource_name": "Browse",
"name": "Browse Catalogue",
"header": "Public Catalogue"
}
};
$(document).ready(function() {
for (var key in pages) {
if (pages.hasOwnProperty(key)) {
//Add a new link for the Menu Navigation Element
document.getElementById('page_nav').innerHTML += "<a id='nav_" + key + "'>"
+ pages[key].name + "</a><br /><br />";
//Create a new callback for the Menu Navigation Element
$('#nav_' + key).click(createCallBack(key));
}
}
});
//Function for returning a callback
function createCallBack(key) {
return function() {
alert("Callback fired");
}
}
你可以找到回答爲什麼的innerHTML不起作用 http://stackoverflow.com/questions/5113105/manipulating-innerhtml-removes-the-event-handler-of-a-child-element – xinyuan