使用JQuery检测段落元素更改 [英] Detect paragraph element change with JQuery
问题描述
是否可以检测JQuery中段落的内容是否已更改?
Is it possible to detect if the content of a paragraph has been changed in JQuery ?
我尝试了以下代码.
<p id="test">Text</p>
<button id="submit1">change</button>
-
$(document).on("click", "#submit1", function () {
var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
$("#test").text(time);
});
$(document).on("change", "#test", function () {
alert("Paragraph changed");
});
JSFiddle: http://jsfiddle.net/nnbqye55/
JSFiddle : http://jsfiddle.net/nnbqye55/
我想我缺少明显的东西.
I guess I am missing something obvious.
推荐答案
change
事件不会在该段落上触发.您所需要的就是 Mutation Observers . 此处是相关的MDN文档.他们具有相当不错的浏览器渗透力;对于较旧的IE,您可以使用已弃用的 Mutation Events ,尽管众所周知,这些事件会导致性能下降,因此请务必小心.我将使用Mutation Observers重写您的示例;您还可以查看 jsFiddle演示 :
change
events won't fire on the paragraph. What you need are known as Mutation Observers. Here is the relevant MDN documentation. They have pretty good browser penetration; for older IEs, you can probably use the deprecated Mutation Events, though those are known to be performance killers, so be very careful. I'll rewrite your example using Mutation Observers; you can also check out a jsFiddle demo:
$(function(){
//Store the test paragraph node
var test = $('#test');
//Function to change the paragraph
var changeParagraph = function () {
var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
test.text(time);
};
//Bind the paragraph changing event
$('#submit1').on('click', changeParagraph);
//Observe the paragraph
this.observer = new MutationObserver( function(mutations) {
alert('Paragraph changed!')
}.bind(this));
this.observer.observe(test.get(0), {characterData: true, childList: true});
});
这篇关于使用JQuery检测段落元素更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!