开发者

event when adding element into document

Adding new html string into the page:

document.getElementById('container').innerHTML = '<div id="child"></div>';

Is there an event that let me know when child element is in the documen开发者_JS百科t?

I have a function, which return some html codeas a string. And when this html will be added in the document, I need to execute javascript function. I've tried to use inline onload event

document.getElementById('container').innerHTML = '<div id="child" onload="console.log(\'ready!\');"></div>';

but it does not seem to work.

UPDATE: Probably, I should provide more details about the situation. I have a library function

myLibrary.getHtml()

In old version, users just call this function and append the result into the document:

document.getElementById('container').innerHTML = myLibrary.getHtml();

In new version, the result is not a plain html. Now users can interact with it after they append it in the document. So after they append html into the document, I need to go through the result DOM and attach event handlers, hide some elements and other things. That is why, I need to know when they add it in the document and execute a javascript function, which turn plain html into fancy interactive widget.


You could try using DOM Mutation Events, but they are still inconsistently implemented across browsers.


If i have not misunderstood the question, you can probably get this to work

document.getElementById('id').childNodes;


If you can use jQuery, you could write your own custom event which would call the function you need to call whenever the new html has been added:

$('#container').bind('changeHtml', function(e) {
  // Execute the function you need
});

And of course instead of just adding the html to the element, you would need to wrap it up in a function which triggers your custom event. Then all you'd need to do is call this function instead of setting the innerHtml yourself.

function addHtml(html) {
  $('#container').innerHTML = html;
  $('#container').trigger('changeHtml');
}


Solved by myself this way:

myLibrary.getHtml = function() {
    var html;
    ...
    var funcName = 'initWidget' + ((Math.random() * 100000) | 0);
    var self = this;
    window[funcName] = function() { self._initWidget(); };
    return html + '<img src="fake-proto://img" onerror="' + funcName + '()"';
}

The idea behind the code is that I specify incorrect url for the src attribute of the img tag and the image triggers error event and call my function. Quite simple :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜