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

后端 未结 3 1617
生来不讨喜
生来不讨喜 2020-12-06 02:18

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.

I have the following JQuery

相关标签:
3条回答
  • 2020-12-06 03:01

    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.

    $(document).ready(function(){
        if($('.classOrId').length){
            //do something if it exists
        };
    });
    
    0 讨论(0)
  • 2020-12-06 03:07

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

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

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

    0 讨论(0)
  • 2020-12-06 03:11

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

    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/

    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 technique provided by a poster on the jQuery forums.

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

    0 讨论(0)
提交回复
热议问题