用于动态添加的div元素的Html div on load事件

Har*_*OTA 9 html javascript

我怎么能做这样的事情?

<div id='myDiv' onload='fnName()'></div>
Run Code Online (Sandbox Code Playgroud)

不能用

window.onload = function () {
    fnName();
};

or

$(document).ready(function () {fnName();});
Run Code Online (Sandbox Code Playgroud)

div元素是动态的.div内容由xml xsl生成.

有任何想法吗?

ale*_*anu 10

您可以使用DOM Mutation Observers

它会在每次dom更改时通知您,例如,当新div插入目标div或页面时.

我正在复制/粘贴exmple代码

// select the target node
var target = document.querySelector('#some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true }

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
observer.disconnect();
Run Code Online (Sandbox Code Playgroud)


Dan*_*eam 9

如果您正在动态注入它,该onload属性可能不会触发<div>(因为文档可能已经加载,但可能它仍然可以工作......?).但是你可以通过简单地做这样的事情来轮询元素(类似于YUI的onContentAvailable):

// when the document has loaded, start polling
window.onload = function () {
    (function () {
        var a = document.getElementById('myDiv');
        if (a) {
            // do something with a, you found the div
        }
        else {
            setTimeout(arguments.callee, 50); // call myself again in 50 msecs
        }
    }());
};
Run Code Online (Sandbox Code Playgroud)

或者你可以改变标记(我对XSL一无所知)是这样的:

在页面的早些时候:

<script type="text/javascript">
    function myDivInserted() {
        // you're probably safe to use document.getElementById('myDiv') now
    }
</script>
Run Code Online (Sandbox Code Playgroud)

使用XSL生成的标记:

<div id="myDiv"></div>
<script type="text/javascript">
    myDivInserted();
</script>
Run Code Online (Sandbox Code Playgroud)

它有点hacky但它​​应该工作.