如何在 jquery 中切换 attr()

我有一个简单的 add 属性函数:

$(".list-toggle").click(function() {
$(".list-sort").attr('colspan', 6);
});

我的问题是: 我怎样才能把它变成一个切换,这样下一次点击时 colspan="6"就从元素中移除了?

161809 次浏览
$('.list-toggle').click(function() {
var $listSort = $('.list-sort');
if ($listSort.attr('colspan')) {
$listSort.removeAttr('colspan');
} else {
$listSort.attr('colspan', 6);
}
});

这里有一个工作小提琴的例子。

看看下面@RienNeVaPlus 给出的更优雅的解决方案。

这将是一个使用 了结的好地方:

(function() {
var toggled = false;
$(".list-toggle").click(function() {
toggled = !toggled;
$(".list-sort").attr("colspan", toggled ? 6 : null);
});
})();

toggled变量只存在于定义的范围内,可用于存储从一个单击事件到下一个单击事件的切换状态。

如果你觉得自己很有想象力:

$('.list-sort').attr('colspan', function(index, attr){
return attr == 6 ? null : 6;
});

Working Fiddle

ES6语法(2021) :

$('.list-sort').attr('colspan', (_, attr) => attr == 6 ? null : 6));

用于只读/禁用和其他具有 true/false 值的属性

$(':submit').attr('disabled', function(_, attr){ return !attr});

我知道这个问题已经过时了,但是我最近不得不实现它,并且决定制作2个简单的 jQuery 插件,它们可能会对感兴趣的人有所帮助

用途:

// 1
$('.container').toggleAttr('aria-hidden', "true");
// 2
$('.container').toggleAttrVal('aria-hidden', "true", "false");

1-无论原始值是否与您提供的值不匹配,都切换整个属性。

在两个提供的值之间切换属性的值。

 // jquery toggle whole attribute
$.fn.toggleAttr = function(attr, val) {
var test = $(this).attr(attr);
if ( test ) {
// if attrib exists with ANY value, still remove it
$(this).removeAttr(attr);
} else {
$(this).attr(attr, val);
}
return this;
};


// jquery toggle just the attribute value
$.fn.toggleAttrVal = function(attr, val1, val2) {
var test = $(this).attr(attr);
if ( test === val1) {
$(this).attr(attr, val2);
return this;
}
if ( test === val2) {
$(this).attr(attr, val1);
return this;
}
// default to val1 if neither
$(this).attr(attr, val1);
return this;
};

下面是您在原始示例中使用它的方式:

$(".list-toggle").click(function() {
$(".list-sort").toggleAttr('colspan', 6);
});
$(".list-toggle").click(function() {
$(this).hasAttr('colspan')
? $(this).removeAttr('colspan')
: $(this).attr('colspan', 6);
});
$(".list-toggle").click(function() {
$(this).attr('colspan')
? $(this).removeAttr('colspan')
: $(this).attr('colspan', 6);
});

这个答案是在计算第二个参数在调用 RemoveAttr 时是无用的! (当这个答案被贴出来的时候)不要在其他情况下使用这个参数!

虽然无法击败 RienNeVaPlus 干净利落的回答,但它也做到了这一点,它基本上是一种更加压缩的三元运算:

$('.list-sort')[$('.list-sort').hasAttr('colspan') ?
'removeAttr' : 'attr']('colspan', 6);

在这些情况下,当需要多次使用引用时,可以使用一个额外的变量:

var $listSort = $('.list-sort');
$listSort[$listSort.hasAttr('colspan') ? 'removeAttr' : 'attr']('colspan', 6);