Wait until HTML elements gets a class then do something

前端 未结 3 551
你的背包
你的背包 2021-02-08 22:16

I am waiting for the document.ready event in order to do something on my page.

Alas some other script, which I cannot change, has not worked its magic yet once my script

3条回答
  •  遥遥无期
    2021-02-08 22:50

    Something like this (pseudo code) :

    var timer = setInterval(function() {
       if (element.className=='someclass') {
           //run some other function 
           goDoMyStuff();
           clearInterval(timer);
       }
    }, 200);
    

    or listen for the element to be inserted:

    function flagInsertedElement(event) {
       var el=event.target;
    }
    document.addEventListener('DOMNodeInserted', flagInsertedElement, false);
    

    jQuery version:

    $(document).on('DOMNodeInserted', function(e) {
        if (e.target.className=='someclass') { 
            goDoMyStuff();
        }
    });
    

    There's also the liveQuery plugin:

    $("#future_element").livequery(function(){
        //element created
    });
    

    Or if this is a regular event handler, delegated events with jQuery's on();

提交回复
热议问题