在布尔属性之间切换 JQuery
Toggle between boolean attributes JQuery
我有一个事件侦听器,我试图在 class(有效)和 true/false(无效)的数据选择属性之间切换。我已经将 div class="dice" 的数据选择属性默认设置为 false。
game.selection = function() {
$(".dice").on("click", function() {
$(this).toggle(function () {
$(this).attr('data-selection', true);
});
$(this).toggleClass("active");
});
};
替换:
$(this).toggle(function () {
$(this).attr('data-selection', true);
});
作者:
$(this).attr('data-selection', ($(this).attr('data-selection') == "false" ? true : false));
最好用data()
function instead of attr()
。您也可以将代码缩减为这样。
$(this).data('selection', ! $(this).data('selection'));
当你像这样将两个参数传递给 .<b>attr</b>(<i>attributeName</i>,<i>value</i>)
, the second param sets the value. You could write a custom extension, similar to toggleClass
to conditionally add or .removeAttr()
时:
(function($) {
$.fn.toggleAttr = function(attributeName, state) {
return this.each(function() {
if (state) {
$(this).attr(attributeName,"")
} else {
$(this).removeAttr(attributeName)
}
});
};
}(jQuery));
然后像这样使用:
$(".class").toggleAttr("boolAt", false);
我有一个事件侦听器,我试图在 class(有效)和 true/false(无效)的数据选择属性之间切换。我已经将 div class="dice" 的数据选择属性默认设置为 false。
game.selection = function() {
$(".dice").on("click", function() {
$(this).toggle(function () {
$(this).attr('data-selection', true);
});
$(this).toggleClass("active");
});
};
替换:
$(this).toggle(function () {
$(this).attr('data-selection', true);
});
作者:
$(this).attr('data-selection', ($(this).attr('data-selection') == "false" ? true : false));
最好用data()
function instead of attr()
。您也可以将代码缩减为这样。
$(this).data('selection', ! $(this).data('selection'));
当你像这样将两个参数传递给 .<b>attr</b>(<i>attributeName</i>,<i>value</i>)
, the second param sets the value. You could write a custom extension, similar to toggleClass
to conditionally add or .removeAttr()
时:
(function($) {
$.fn.toggleAttr = function(attributeName, state) {
return this.each(function() {
if (state) {
$(this).attr(attributeName,"")
} else {
$(this).removeAttr(attributeName)
}
});
};
}(jQuery));
然后像这样使用:
$(".class").toggleAttr("boolAt", false);