为什么在以下代码中添加元素时未触发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函数未被触发的问题?
答案 0 :(得分:1)
这是你想要的吗?
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>
答案 1 :(得分:1)
尝试使用DOMSubtreeModified
事件:
function create() {
var para = document.createElement("p");
$("body").on('DOMSubtreeModified', para, myFunction());
//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);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
&#13;