[英]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: HTML:
<li class="media-thumb" data-select="false"><img src="IMG HERE"></li>
Javascript: 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. data-select
属性将返回为boolean false
(根据jQuery docs :“已尝试将字符串转换为JavaScript值”),而不是字符串。
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 示例代码笔: http ://codepen.io/paulroub/pen/Bnvub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.