r0n*_*y1l 3 javascript dom google-chrome
假设我有这样的跨度
<span id="theSpan"></span>
Run Code Online (Sandbox Code Playgroud)
使用WebKitMutationObserver(我正在开发chrome的扩展,所以不用担心跨浏览器问题),我如何监听跨度内的变化(innerText)?即.当我这样做时,事件应该触发:
Javascript
$("#theSpan").text('hello world');
Run Code Online (Sandbox Code Playgroud)
HTML
<span id="theSpan">Hello World</span>
Run Code Online (Sandbox Code Playgroud)
您需要创建WebKitMutationObserver实例,然后将其附加到您的<span>using observe方法.代码如下所示:
// find element and create an observer instance
var target = $('#theSpan');
var observer = new WebKitMutationObserver(function(mutations) {
$('#log').text('input text changed: "' + target.text() + '"');
});
observer.observe(target[0], { childList: true});
//observer.disconnect(); - call this to stop observing
// test case
setInterval(function(){
target.text('hello world ' + Math.random() + '!!!');
},1000);
?
Run Code Online (Sandbox Code Playgroud)
不要忘记将真正的DOM对象传递给observer,而不是jQuery对象.这里有工作小提琴