簡體   English   中英

如何將事件添加到使用JS創建的元素?

[英]How to add event to element created with js?

我在下面創建了腳本。 根據需要將其放入div中。 但是,事件處理程序失敗。 我敢肯定這是一個簡單的錯誤。

body_html = document.body.innerHTML;
new_html = "<div id='realBody'>" + body_html + "</div>";
document.body.innerHTML = new_html;
document.body.getElementById("realBody").addEventListener("mouseover", function(event) {alert('body');});

如何使活動進行? (如果有更好(更簡單)的方法,請隨意重寫整個內容。

編輯:這有效,一些評論說這是將主體放入div的錯誤方法,但我認為沒有問題:

body_html = document.body.innerHTML;
new_html = "<div id='realBody'>" + body_html + "</div>";
document.body.innerHTML = new_html;
document.getElementById("realBody").addEventListener("mouseenter", function(event) {alert('body');});

謝謝!

您應該附加事件監聽器,例如

body_html = document.body.innerHTML;
new_html = "<div id='realBody'>" + body_html + "I am border</div>";
document.body.innerHTML = new_html;
document.getElementById("realBody").addEventListener("mouseover", function (event) {
    alert('body');
});

演示

您需要將document.body.getElementById()更改為document.getElementById()

document.getElementById("realBody").addEventListener("mouseover", function(event) {alert('body');});

您收到的錯誤可能是由於以下原因:

document.body.getElementById("realBody").addEventListener("mouseover", function (event) { alert('body'); });

您需要對此進行修改:

document.getElementById("realBody").addEventListener("mouseover", function (event) { alert('body'); });

document.body.getElementById()只需是document.getElementByid()

將元素添加到DOM的更合適的方法是執行以下操作:

var divEl = document.createElement("div");
divEl.id = "realBody";
var textNode = document.createTextNode("Hover over me");
divEl.appendChild(textNode);
document.body.appendChild(divEl);

divEl.onmouseover = function (event) {
    alert('body');
}

正如大家所解釋的,您需要在文檔對象上而不是在元素中調用getElementById()。

但是,當您清除html並覆蓋了innerHTML的情況下創建新的dom結構時,您的代碼將在執行代碼之前松動附加到元素的所有事件處理程序。

而是將現有dom移至新元素,例如

var wrapper = document.createElement('div');
wrapper.id = 'realBody';
while (document.body.firstChild) {
    wrapper.appendChild(document.body.firstChild);
}
document.body.appendChild(wrapper);
wrapper.addEventListener("mouseover", function (event) {
    console.log('body');
});

演示: 小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM