JQuery 不会在 $(document).change() 上执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12495128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:44:59  来源:igfitidea点击:

JQuery does not execute on $(document).change()

jquerycssasp.net-mvc

提问by Theomax

I need to make some JQuery execute when the page/document has changed - in this case, when a div with a specific CSS class is displayed.

当页面/文档发生变化时,我需要执行一些 JQuery - 在这种情况下,当显示具有特定 CSS 类的 div 时。

I have the following JQuery code:

我有以下 JQuery 代码:

   <script>
           $(document).change(function () {
               if ($('.validation_errors').length) {
                   alert("test");
               }
           }
    </script>

However, it does not execute and display the alert. Am I missing something here?

但是,它不会执行和显示警报。我在这里错过了什么吗?

回答by noj

Change is only for input, textarea or select elements. Instead you need to bind a function to the DOMSubtreeModifiedmutation event:

更改仅适用于 input、textarea 或 select 元素。相反,您需要将函数绑定到DOMSubtreeModified突变事件:

$(document).bind('DOMSubtreeModified', function () {
   if ($('.validation_errors').length) {
       alert("test");
   }
});

EDIT: If your target browsers support it, you should use a MutationObserverinstead.

编辑:如果您的目标浏览器支持它,您应该改用MutationObserver

回答by Josh Davenport

You can't monitor changes in the DOM is this manner. Quote from the jQuery docs:

您不能以这种方式监视 DOM 中的更改。引用自 jQuery 文档:

The change event is sent to an element when its value changes. This event is limited to elements, boxes and elements. - http://api.jquery.com/change/

当元素的值发生变化时,将更改事件发送到元素。此事件仅限于元素、框和元素。- http://api.jquery.com/change/

If you're looking to execute code when there is a DOM change, you may need to either set up and interval which checks the DOM or use this techniqueprovided by a poster on the jQuery forums.

如果您希望在 DOM 更改时执行代码,您可能需要设置和间隔检查 DOM,或者使用jQuery 论坛上的海报提供的这种技术

There is the DOMSubtreeModifiedevent, but it is scarcely available in current browsers, so I personally wouldn't recommend its use. See this stackoverflow answerfor further details on that

有这个DOMSubtreeModified事件,但它在当前浏览器中几乎不可用,所以我个人不推荐使用它。有关更多详细信息,请参阅此 stackoverflow 答案

回答by Shannon

Your syntax is wrong too buddy! If you're going to do it, do it within document ready, .change is very limited and wont fire on a new page.

哥们你的语法也错了!如果您打算这样做,请在准备好的文档内进行,.change 非常有限,不会在新页面上触发。

$(document).ready(function(){
    if($('.classOrId').length){
        //do something if it exists
    };
});