This question already has answers here:
How to add onload event to a div element
                                
                                    (22个答案)
                                
                        
                2年前关闭。
            
        

为什么在以下代码中添加元素时未触发onload事件:



function create() {
var para = document.createElement("p");

para.setAttribute('onload', 'myFunction');

var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");
element.appendChild(para);


}

function myFunction() {
  alert(1);
}

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<br>

<button onclick="create()">create</button>





这不是在元素上设置属性的正确方法,还是onload函数未触发的问题?

最佳答案

这是你想要的吗?



function create() {
var para = document.createElement("p");

var node = document.createTextNode("This is new.");
para.appendChild(node);

para.onload = myFunction();

var element = document.getElementById("div1");
element.appendChild(para);


}

function myFunction() {
  alert(1);
}

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<br>

<button onclick="create()">create</button>

关于javascript - 以编程方式添加的属性中的onload事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49537905/

10-15 09:57