Javascript 在布尔属性JQuery之间切换
我有一个事件监听器,我试图在类(正在工作)和数据选择属性true/false(不工作)之间切换。默认情况下,我已经将div class=“dice”的数据选择属性设置为falseJavascript 在布尔属性JQuery之间切换,javascript,jquery,events,click,toggle,Javascript,Jquery,Events,Click,Toggle,我有一个事件监听器,我试图在类(正在工作)和数据选择属性true/false(不工作)之间切换。默认情况下,我已经将div class=“dice”的数据选择属性设置为false game.selection = function() { $(".dice").on("click", function() { $(this).toggle(function () { $(this).attr('data-selection', true); }); $(t
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).data('selection', ! $(this).data('selection'));
将两个参数传递给时,第二个参数将设置值。您可以编写一个自定义扩展,类似于有条件地添加或类似以下内容:
(函数($){
$.fn.toggleAttr=函数(attributeName,state){
返回此值。每个(函数(){
如果(州){
$(this.attr(attributeName,“”)
}否则{
$(this).removeAttr(attributeName)
}
});
};
}(jQuery));
然后像这样使用:
$(“.class”).toggleAttr(“boolAt”,false);
我对代码进行了更多的修改,并将其应用到某种工作中:$(“.dice”).on(“click”,function(){if($(this).attr($(data-selection',false)){$(this).attr($(data-selection',true);}$(this.toggleClass(“active”);});现在的问题是,它在单击时将数据选择更改为true,但在第二次单击时不会切换回false。$(this).attr('data-selection',$(this).attr('data-selection')==“false”)代码>$(this.attr($(this.attr('data-selection')=“false”?true:false))
与$(this.attr('data-selection',$(this.attr('data-selection')=“false”)相同代码>上面有评论:)我同意,我在发布我的答案后看到了你的评论。(我开始写的时候它不在那里)如果他使用.attr()
设置数据,那么使用.data()
会起作用吗?@guradio不,不会。
$(this).data('selection', ! $(this).data('selection'));