Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

javascript - Html div on load event for a dynamically added div element

How i can make some thing like this?

<div id='myDiv' onload='fnName()'></div>

can't use

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

or

$(document).ready(function () {fnName();});

the div element is dynamic. The div content is generated by xml xsl.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The onload attribute probably wouldn't fire on the <div> if you're injecting it dynamically (as the document is likely already loaded, but maybe it'd still work...?). However you could either poll for the element by simply doing something like this (similar to YUI's 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
        }
    }());
};

Or you could change the markup (I know nothing about XSL) to be something like this:

Earlier on in the page:

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

The markup you generate with XSL:

<div id="myDiv"></div>
<script type="text/javascript">
    myDivInserted();
</script>

It's a bit hacky but it should work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...