简体   繁体   English

jQuery if else语句和数据()

[英]jQuery if else statements and data()

I've been struggling over this for almost 5 hours and finally I've got a clue. 我已经苦苦挣扎了近5个小时,最后我有了一个线索。

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. 这是jfiddle。

http://jsfiddle.net/Fe678/ 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? 当我在我的WordPress页面(localhost)上尝试相同的确切代码时,它会一个接一个地显示两个警报 - “数据未设置”然后“数据已设置” - 可能导致这种奇怪行为的原因是什么?

Unfortunately I can't provide the source. 不幸的是我无法提供来源。 I'm hoping this is something common and maybe some jQuery wizard will know the answer? 我希望这是常见的,也许一些jQuery向导会知道答案吗? Somehow...? 不知何故...?

I don't think it's a jQuery bug, but one of the following: 我不认为这是一个jQuery错误,但以下之一:

  • Your WordPress templates eventually cause the code to be included twice. 您的WordPress模板最终会导致代码被包含两次。 To debug this, put an alert before the call to .bind() and verify you see it only once. 要调试它,请在调用.bind()之前发出警报,并验证您只看到一次。
  • For some reason in your WordPress version you actually have two overlapping '.thumbnail' class objects, and "click" triggers both of them. 出于某种原因,在你的WordPress版本中,你实际上有两个重叠的'.thumbnail'类对象,而“click”会触发它们。 If you wrap one of your thumbnails on jsfiddle with extra <DIV class=thumbnail> you will see how this happens. 如果你使用额外的<DIV class = thumbnail>在jsfiddle上包装你的一个缩略图,你会看到这是如何发生的。 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. 要调试它,请放入一个警告框,显示调用该方法的对象,并验证您没有两个单独的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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