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

标签 javascript jquery html

根据jQuery documentation page.change()每当 value 时,方法就会调用处理函数相关元素的变化。但该方法仅限于 <input> , <textarea> ,和<select>元素。

我怎样才能对 <p> 做同样的事情?元素(和其他元素)当其 innerHTML变化?如果能找到一个简单的 jQuery 函数来完成此任务,那就太好了。

最佳答案

MutationObserver provides developers with a way to react to changes in a DOM. It is designed as a replacement for Mutation Events defined in the DOM3 Events specification.

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

关于javascript - 适用于 HTML <p> 元素文本的 jQuery .change() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49540900/

相关文章:

javascript - 招聘时测试 HTML/CSS/Javascript 技能

javascript - 在 jquery 中通过列表项值选择的预填充列表项

php - 使用 Ajax/Json 更新 Mysql 记录不起作用

html - Bootstrap 折叠菜单有 2 行

javascript - 如何使用 ajax 回调更新/填充多个输入字段?

javascript - 了解 javascript 中的回调和闭包

javascript - react 路由器错误 - 'Cannot call method ' getRouteAtDepth' of undefined'

javascript - 使用 JSON 自动完成

html - 我想向移动设备Opencart显示不同的背景

html - CSS :last-of-type not working in combination with :not