Detect element content changes with jQuery

后端 未结 15 2250
余生分开走
余生分开走 2020-11-22 04:19

change() function works and detects changes on form elements, but is there a way of detecting when a DOM element\'s content was changed?

This does not w

15条回答
  •  旧巷少年郎
    2020-11-22 04:57

    I know this post is a year old, but I'd like to provide a different solution approach to those who have a similar issue:

    1. The jQuery change event is used only on user input fields because if anything else is manipulated (e.g., a div), that manipulation is coming from code. So, find where the manipulation occurs, and then add whatever you need to there.

    2. But if that's not possible for any reason (you're using a complicated plugin or can't find any "callback" possibilities) then the jQuery approach I'd suggest is:

      a. For simple DOM manipulation, use jQuery chaining and traversing, $("#content").html('something').end().find(whatever)....

      b. If you'd like to do something else, employ jQuery's bind with custom event and triggerHandler

      $("#content").html('something').triggerHandler('customAction');
      
      $('#content').unbind().bind('customAction', function(event, data) {
         //Custom-action
      });
      

    Here's a link to jQuery trigger handler: http://api.jquery.com/triggerHandler/

提交回复
热议问题