一个适用于HTML <p>元素文本的jQuery .change()方法

时间:2018-03-28 17:38:59

标签: javascript jquery html

根据jQuery documentation page,只要有问题的元素的.change()发生变化,value方法就会调用一个处理函数。但是,此方法仅限于<input><textarea><select>元素。

如果<p>元素(和其他元素)的innerHTML发生变化,我怎么能这样做呢?很高兴找到一个简单的jQuery函数来完成这个。

1 个答案:

答案 0 :(得分:1)

  

MutationObserver为开发人员提供了一种对DOM中的更改做出反应的方法。它被设计为DOM3事件规范中定义的Mutation事件的替代。

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

这里也是jQuery的库:https://github.com/joelpurra/jquery-mutation-summary

// Use document to listen to all events on the page (you might want to be more specific)
var $observerSummaryRoot = $(document);

// Simplest callback, just logging to the console
function callback(summaries){
    console.log(summaries);
}

// Connect mutation-summary
$observerSummaryRoot.mutationSummary("connect", callback, [{ all: true }]);