如何在 jquery 中切换 attr()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18665031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:10:32  来源:igfitidea点击:

how to toggle attr() in jquery

jquery

提问by alias51

I have a simple add attribute function:

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

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

My question is: how can I turn this into a toggle, so colspan="6"is removed from the element on the next click?

我的问题是:如何将其转换为切换,以便colspan="6"在下次单击时从元素中删除?

回答by RienNeVaPlu?s

If you're feeling fancy:

如果你觉得很花哨:

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

Working Fiddle

工作小提琴

回答by musicnothing

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

Here's a working fiddle example.

这是一个有效的小提琴示例。

See the answer by @RienNeVaPlus below for a more elegant solution.

请参阅下面@RienNeVaPlus 的答案以获得更优雅的解决方案。

回答by BitOfUniverse

For readonly/disabled and other attributes with true/false values

对于 readonly/disabled 和其他具有 true/false 值的属性

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

回答by Francisc0

I know this is old and answered but I recently had to implement this and decided to make 2 simple jQuery plugins that might help for those interested

我知道这是旧的和回答但我最近不得不实现这个并决定制作 2 个简单的 jQuery 插件,可能对那些有兴趣的人有所帮助

usage:

用法:

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

1 - Toggles the entire attribute regardless if the original value doesn't match the one you provided.

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

2 - Toggles the value of the attribute between the 2 provided values.

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

 // 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;
  };

This is how you would use it in the original example:

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

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

回答by thirdender

This would be a good place to use a closure:

这将是使用闭包的好地方:

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

The toggledvariable will only exist inside of the scope defined, and can be used to store the state of the toggle from one click event to the next.

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

回答by mangonights

For what it's worth.

物有所值。

$('.js-toggle-edit').on('click', function (e) {
    var bool = $('.js-editable').prop('readonly');
    $('.js-editable').prop('readonly', ! bool);
})

Keep in mind you can pass a closure to .prop(), and do a per element check. But in this case it doesn't matter, it's just a mass toggle.

请记住,您可以将闭包传递给 .prop(),并进行每个元素的检查。但在这种情况下,这并不重要,它只是一个质量切换。

回答by Zuks

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

回答by user2398069

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

回答by Daniel

This answer is counting that the second parameter is useless when calling removeAttr! (as it was when this answer was posted)Do not use this otherwise!

这个答案算在调用removeAttr时第二个参数没用! (就像发布此答案时一样)否则不要使用它!

Can't beat RienNeVaPlus's clean answer, but it does the job as well, it's basically a more compressed way to do the ternary operation:

无法击败RienNeVaPlus 的简洁答案,但它也能完成这项工作,它基本上是一种更压缩的三元运算方式:

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

an extra variable can be used in these cases, when you need to use the reference more than once:

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

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