我在使用JavaScript定向動態創建的元素時遇到了一些問題。有關動態創建的HTML的事件的JavaScript問題
問題1
縮短JavaScript代碼:
var lightbox = document.createElement('div'),
nav = document.createElement("nav"),
imga = document.querySelectorAll(".gallery a");
for (i = 0; i < imga.length; i++) {
imga[i].addEventListener("click", function() {
document.body.insertBefore(lightbox, document.body.firstChild);
lightbox.appendChild(nav);
});
}
1:現在我要讓我的<nav>
的事件。我如何獲得該活動的目標是#lightbox nav a
而不僅僅是#lightbox nav
?
nav.addEventListener("click", function() {
// works, but I want to target only the <a> links inside
});
我試過很多東西,像這樣:
var selector = document.querySelectorAll("nav a");
for (i = 0; i < selector.length; i++) {
selector[i].addEventListener("click", function() {
// doesn't work because the <nav> is inserted dynamically
});
}
這:
var selector = nav.getElementsByTagName("a");
for (i = 0; i < selector.length; i++) {
selector[i].addEventListener("click", function() {
// doesn't work because the <nav> is inserted dynamically
});
}
第2期
縮短JavaScript代碼:
var img,
imga = document.querySelectorAll(".gallery a");
for (i = 0; i < imga.length; i++) {
imga[i].addEventListener("click", function() {
for (i = 0; i < imga.length; i++) {
img = document.createElement("img");
lightbox.appendChild(img);
}
});
}
2:如何將事件添加到動態創建的#lightbox img
?該img = document.createElement("img")
必須追加多個圖像的功能裏面,因爲這個原因,我不能做這樣的(就像目前<nav>
):
img.addEventListener("click", function() {
// doesn't work because img = document.createElement("img")
// has to be inside another function
});
有人可以請幫我在這?我在JavaScript方面經驗不足。
這是很好的問題。 +1 –