在布尔属性JQuery之间切换

Toggle between boolean attributes JQuery

本文关键字:之间 JQuery 布尔 属性      更新时间:2023-09-26

我有一个事件侦听器,我正试图在类(有效)和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()函数而不是attr()。您也可以将代码简化为这样。

$(this).data('selection', ! $(this).data('selection'));

将两个参数传递给.attr(attributeName,value)时,第二个参数设置值。您可以编写一个自定义扩展,类似于toggleClass来有条件地添加或.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);