【问题标题】:onload event in programmatically added attribute [duplicate]以编程方式添加的属性中的 onload 事件 [重复]
【发布时间】:2018-03-28 23:05:48
【问题描述】:

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

【问题讨论】:

标签: javascript html


【解决方案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>

【讨论】:

    【解决方案2】:

    尝试使用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);
    }
    <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>

    【讨论】:

      猜你喜欢
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      相关资源
      最近更新 更多