以编程方式添加的属性

时间:2018-03-28 14:58:52

标签: javascript html

为什么在以下代码中添加元素时未触发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函数未被触发的问题?

2 个答案:

答案 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事件:

&#13;
&#13;
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;
&#13;
&#13;