开发者

jQuery: Is there an event that's triggered by data insertion into a HTML element, say div?

Say that I have a <div id="notification"> which has empty content to start with. The server will ajaxly inserts some content into it l开发者_StackOverflow社区ater on. Is there an event that's triggered by this insertion? Thanks.

Note I am using jQuery as my js framework.


you can trigger a custom event:

function addContentToDiv(div, markup) {

    // NOTE: div is a jQuery object:
    div.html(markup);
    div.trigger('myDivHtmlChanged');
}

Then, to use it:

$(document).ready(function() {
    $('myDiv').bind('myDivHtmlChanged', function() {
        alert('content changed in myDiv');
    });
});


Yes, there is, but you can't rely on the browser supporting it. Instead, you want to hook into the ajax call, perhaps via ajaxComplete or one of its brethren.


There is the global ajaxComplete event that is triggered by jQuery: http://api.jquery.com/ajaxComplete/

Description: Register a handler to be called when Ajax requests complete. This is an Ajax Event.

$('.selector').ajaxComplete(function(e) {
    // add bling
});


When I want to know I have inserted data using ajax, I setup up a custom jQuery event on the divs in question.

$(document).ready(function(){

  $("#notification").bind("ajaxComplete", function(event){
     alert("updated");
  });

  $("#notification").load("/hello.html", function(responseText, textStatus, XMLHttpRequest){
    $("#notification").trigger("ajaxComplete");
  });

});


There is no event triggered by that insertion on a DIV. Change event will trigger on form elements.


What you're looking for are the DOMNodeInserted, DOMNodeRemoved, etc... events:

$("body").bind("DOMNodeInserted", function(e) { 
    var insertedNode = $(e.target);
    ...
});

But, like T.J. said, these aren't exactly browser friendly. In fact they won't work in any version of IE. You can find a complete list of DOM events and their browser support at: http://www.quirksmode.org/dom/events/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜