有没有一种方法可以让内联事件处理程序在元素创建后立即执行

Is there a way to have an inline event handler which will be executed as soon as the element has been created?

本文关键字:元素 程序 事件处理 创建 执行 一种 方法 有没有      更新时间:2023-09-26

我尝试了onload,但它不起作用:

var divElement = document.createElement('div');
divElement.innerHTML = '<div onload="alert(this)"></div>';

什么";关于";我可以使用内联Javascript使用处理程序来实现这一点吗?

JQuery中有一种方法可以做到这一点。我已经提到了下面的代码片段。点击"运行代码段"获得代码演示。

$( "#book" ).load(function() {
   
  alert('element loaded')
  $(this).addClass("imgHeight")
});
.imgHeight{ height:150px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://quadrobay.com/quadrobay/images/fsolution.png" alt="Book" id="book">