【问题标题】:A jQuery .change() method that works for HTML <p> element text [duplicate]适用于 HTML <p> 元素文本的 jQuery .change() 方法[重复]
【发布时间】:2018-09-07 12:23:18
【问题描述】:

根据jQuery documentation page,只要相关元素的value 发生变化,.change() 方法就会调用处理函数。但是,此方法仅限于&lt;input&gt;&lt;textarea&gt;&lt;select&gt; 元素。

&lt;p&gt; 元素(和其他元素)的 innerHTML 发生变化时,我该如何做同样的事情?如果能找到一个简单的 jQuery 函数就可以了。

【问题讨论】:

  • 他们都不回答你的问题吗(例如this one)?或者您想知道是否有更现代的方法?
  • @Kyle 在您提到的the question 解决了我的问题。但是那里的答案都没有回答我的具体问题,我想知道是否有更现代的方法,特别是如果该方法包含一个非常简单的 jQuery 调用。

标签: javascript jquery html


【解决方案1】:

MutationObserver 为开发人员提供了一种对 DOM 中的变化做出反应的方法。它旨在替代 DOM3 事件规范中定义的突变事件。

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 }]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    相关资源
    最近更新 更多