聆听DIV内的变化并采取相应行动

Chr*_*ris 43 jquery

我有一个功能,它抓取XML文档并根据XSL文档进行转换.然后将结果放入带有id的div中laneconfigdisplay.我想要做的是,与转换逻辑分开,为该div设置jQuery更改事件,以便我可以告诉它何时更改,并运行一些jQuery代码.

我尝试了以下,但它不起作用!

$(document).ready(function()
{
    $('#laneconfigdisplay').change(function() {
        alert('woo');
    });
    //Do XML / XSL transformation here
});

<!-- HTML code here -->
<div id="laneconfigdisplay"></div>
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Shi*_*iki 80

您可以选择创建自己的自定义事件,这样您仍然可以清楚地分离逻辑.

绑定到自定义事件:

$('#laneconfigdisplay').bind('contentchanged', function() {
  // do something after the div content has changed
  alert('woo');
});
Run Code Online (Sandbox Code Playgroud)

在更新div的函数中:

// all logic for grabbing xml and updating the div here ..
// and then send a message/event that we have updated the div
$('#laneconfigdisplay').trigger('contentchanged'); // this will call the function above
Run Code Online (Sandbox Code Playgroud)


kim*_*3er 13

change活动仅限于input,textareaselect.

有关更多信息,请访问http://api.jquery.com/change/.


meo*_*meo 10

http://api.jquery.com/change/

更改仅适用于输入表单元素.

您可以在XML/XSL转换后触发函数或创建一个监听器:

var html = $('#laneconfigdisplay').html()
setInterval(function(){ if($('#laneconfigdisplay').html() != html){ alert('woo'); html = $('#laneconfigdisplay').html() } }, 10000) //checks your content box all 10 seconds and triggers alert when content has changed...
Run Code Online (Sandbox Code Playgroud)

  • 不断轮询DOM并不是一个好主意.变更应仅在发生变化时以及在发生变化的情况下报告,例如@ Shiki的"绑定"示例. (4认同)
  • 当事情发生变化时,为什么你可以每10秒检查一次事件? (2认同)

Moh*_*jib 5

尽管该事件DOMSubtreeModified已被弃用,但到目前为止它仍在运行,因此对于任何临时项目,您都可以按以下方式使用它。

$("body").on('DOMSubtreeModified', "#mydiv", function() {
    alert('changed');
});
Run Code Online (Sandbox Code Playgroud)

从长远来看,您将不得不使用MutationObserver API。