简体   繁体   中英

jQuery if else statements and data()

I've been struggling over this for almost 5 hours and finally I've got a clue.

Here's a code that I'm using on my website:

jQuery(document).ready(function(){
    jQuery(".thumbnail").bind("click",function(){
    var elem = jQuery(this);
        if((elem).data('test')) {
            alert('data is test');
            elem.data('test',false);
        }
        else {
            alert('data is not test');
            elem.data('test',true);
        }
    });
});

Here's jfiddle.

http://jsfiddle.net/Fe678/

When you click on "thumbnail" it should fire one alert (either "data is test" or "data is not test").

When I try the same exact code on my WordPress page (localhost) it shows TWO alerts one after another - "data is not set" and then "data is set" - what may cause this strange behavior?

Unfortunately I can't provide the source. I'm hoping this is something common and maybe some jQuery wizard will know the answer? Somehow...?

I don't think it's a jQuery bug, but one of the following:

  • Your WordPress templates eventually cause the code to be included twice. To debug this, put an alert before the call to .bind() and verify you see it only once.
  • For some reason in your WordPress version you actually have two overlapping '.thumbnail' class objects, and "click" triggers both of them. If you wrap one of your thumbnails on jsfiddle with extra <DIV class=thumbnail> you will see how this happens. To debug this, put in an alert box that shows the object on which the method is being called and verify that you don't have two separate objects there.

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