0

I put in the alerts because the changes were not showing when I did inspect element. However, when I click on the object the first time it brings up the "data is now false" alert as if I had already clicked it once.

HTML:

<li class="media-thumb" data-select="false"><img src="IMG HERE"></li>

Javascript:

 $(document).ready(function() {


    $(".media-thumb").click(function() {
        if($(this).data("select") === "false") 
            {
                alert("data is now true")
                $(this).data("select", "true");


            }
        else
            {
                alert("data is now false")
                $(this).data("select", "false");

            }
    });

});
4

1 回答 1

3

data-select属性作为布尔值返回false(根据jQuery 文档:“每次尝试都将字符串转换为 JavaScript 值”),而不是字符串。

所以你实际上可以写:

$(".media-thumb").click(function() {
    if(! $(this).data("select")) 
        {
            alert("data is now true")
            $(this).data("select", true);
        }
    else
        {
            alert("data is now false")
            $(this).data("select", false);
        }
});

示例 CodePen:http ://codepen.io/paulroub/pen/Bnvub

于 2013-09-20T03:14:44.620 回答