当<ul>内容改变时调用jquery函数

Jal*_*tel 15 html javascript jquery

当ul内容改变时,我尝试调用jQuery函数.

以下是我的代码

JS

jQuery(document).ready(function($) {

        $('.ProductList').live('change', function() {
          alert('content is changed now');
        });
    });
Run Code Online (Sandbox Code Playgroud)

HTML

<ul class='ProductList List Clear'>
call jquery function when content change here.
     <li></li>
     <li></li>
      <li></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

建议我一些想法,所以我可以解决它.

我尝试基于内容更改调用函数,因为我从事bigcoomerce定制和大型商务不允许我访问ajax函数,因为访问受限,所以我需要调用这样的函数.

num*_*web 7

这是一个迟到的回应,但我分享它面对同样问题的新开发者;

有些人可能会建议使用MutationEvents但要小心,因为这已被弃用!

$('.ProductList').on('DOMSubtreeModified', function(event) {
    // dos tuff
});
Run Code Online (Sandbox Code Playgroud)

推荐的方法是使用MutationObserver,就像在这个问题中解释的那样,但要注意它在IE8等旧浏览器中不受支持!


A. *_*lff 5

测试:{如果特定的ajax请求设置为global false,这将不起作用}

! function () {
    var ulContent;
    $(document).ajaxStop(function () {
        var $ul = $('.ProductList');
        if(ulContent !== $ul.html()){
            ulContent = $ul.html();
            $ul.trigger('contentChanged');
        }
    });
}();

$('.ProductList').on('contentChanged',callback);
Run Code Online (Sandbox Code Playgroud)

回调是UL内容发生变化时要调用的函数.您应该直接从ajaxStop处理程序调用它,但通常我们使用自定义事件.

如果您不知道以前的语法意味着什么,请使用它:

 $('.ProductList').on('contentChanged',function(){alert('UL content changed!!!');});
Run Code Online (Sandbox Code Playgroud)

  • @ user1692342 http://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function在缩小代码时这很有用 (2认同)