简体   繁体   中英

Using JQuery to edit Data attributes on specific DOM elements

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");

            }
    });

});

The data-select attribute is being returned as boolean false (per the jQuery docs : "Every attempt is made to convert the string to a JavaScript value"), not a string.

So you can actually write:

$(".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);
        }
});

Example CodePen: http://codepen.io/paulroub/pen/Bnvub

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