开发者

Fire a jQuery function at runtime [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Detect element content changes with jQuery

I have a wrapper div say

<div id="placesNewCheckinContainer" style="display:none">
</div>

If at run time any Dom element is inserted/Deleted inside that placesNewChecki开发者_StackOverflow中文版nContainer, I want a fire a jQuery function. Help me how to implement this. Thanks


There's no convenient way of doing this in a totally cross browser manner. Firefox, Chrome and Safari all support the DOMSubtreeModified event which will fire for any modifications to the DOM inside a particular element. The aforementioned browsers and Opera support DOMNodeInserted and DOMNodeRemoved, which will also do the job.

$("#placesNewCheckinContainer").bind("DOMNodeInserted DOMNodeRemoved", function () {
    alert("Something happened inside #placesNewCheckinContainer");
});

Unfortunately, IE doesn't support any of those events. It does have its own event that can partially do the job, however - onpropertychange. This can notify you when the value of innerHTML changes, but only for modifications to direct children, not all descendants.


The only way I am aware of to handle this type of situation is Mutation events.

http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents

These events are still not widely supported; however you have events like

  • onsubtreemodified
  • onnodeinserted
  • onnoderemoved
  • ondomnoderemovedfromdocument
  • ondomnodeinsertedintodocument
  • onattrmodified
  • oncharacterdatamodified

You may also want to look at similar posts like:

Detect element content changes with jQuery


jQuery has a change event, but it is only used on user input fields (browser fires these events). The manipulation of the DIV you listed has to be coming from code. So why not find where the manipulation occurs and then add whatever logic you need to there instead?

I found a great article a while back "Custom events in jQuery open doors to complex behaviors"

This covers some cool things you can do with custom binding. But you still need to fire a trigger, which means manipulating the code that alters the div's contents to fire the trigger, or setting an timed interval to monitor the contents of the div for a change which would fire the trigger (which I would not recommend - as its not instant and causes unnecessary overhead).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜