我瀏覽了其他答案,但找不到解決此問題的方法。將事件監聽器添加到動態創建的按鈕
我有這樣的HTML:
<body>
<h1>Javascript in the Browser</h1>
<div id="removeReference">
</div>
<div>
<p>This page looks a little sad without any style...</p>
<button id="styleButton">Apply some style!</button>
</div>
<div id="imagePlaceholder">
</div>
<script src="script.js"></script>
</body>
在JavaScript文件,我有一個函數stylePage
是通過點擊一個按鈕觸發並把它添加一些樣式,刪除按鈕本身,並創建一個新的按鈕。 在這一點上,我想添加一個事件到這個動態創建的新按鈕,以便點擊時觸發功能createImage
。
我知道使用庫會更好,但這是嘗試自學JavaScript。 我想也許有可能從stylePage
返回按鈕,並將事件偵聽器添加到返回值,但沒有奏效。 任何建議非常感謝,謝謝!
function stylePage(){
var body = document.getElementsByTagName("body");
body[0].style.backgroundColor = "rgb(214, 214, 214)";
body[0].style.color = "#778899";
body[0].style.fontFamily = "Courier";
body[0].style.textAlign = "center";
var remove = document.getElementById("removeReference");
remove.nextElementSibling.remove();
var newButton = document.createElement("button");
var newContent = document.createTextNode("Not enough?");
newButton.appendChild(newContent);
document.body.insertBefore(newButton, remove);
};
function createImage(){
var img = document.createElement("img");
img.src = "pepsi_dog_by_werelyokoman.jpg";
document.getElementById("imagePlaceholder").appendChild(img);
}
var button = document.getElementsByTagName("button");
button[0].addEventListener("click", stylePage);
//??? reference to newButton ??? .addEventListener("click", createImage);
你會發現這篇文章有幫助:https://davidwalsh.name/event-delegate – SimianAngel
HTTP://計算器.com/questions/1687296/what-is-dom-event-delegation –
感謝關於事件代表團的信息! – HiFi