简体   繁体   中英

How can I detect a css class added dynamically

I have an html element in which we add a css class dynamically after a while of loading the main page. When i try in JQuery to detect if this element has the added class, the hasClass method return false.I suggest that is because the element has been dynamically added .

My code it is inserted inside the $(document).ready(function() {}); .

Javascript:

!$('#travel-1_1_').hasClass('complete');

HTML:

<rect id="travel-1_1_" width="64" height="12.6" y="28.5" x="48" class="complete"></rect>

You need to make your function run at an interval after the page has loaded. Here's one option:

function fn60sec() {
// runs every 60 sec and runs on init.
$('#travel-1_1_').hasClass('complete');
}
fn60sec();
setInterval(fn60sec, 60*1000);

您可能需要在设置类的同一位置进行检查,以确保仅在之后执行

Where are you checking if the class exists?

According to this answer, you should be able to just check it inside the $(document).ready() function.

My first suggestion would be to just call whatever function you need when you add the class. In the case that you don't control the code adding the class though I think the best thing to do would be to set an Interval listener.

var classListener = setInterval(function(){
    if($('#travel-1_1_').hasClass('complete')){
        clearInterval(classListener);
        //Do your work here or
        doWorkFunctionCall();
    }
}, 1000);

The unit for the interval is milliseconds, so this will run every second. if you want it to take longer just multiply it by how many seconds you want it to wait before checking. The advantage to this solution is that it will stop running once it finds that the element has the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM