Javascript 如何使用 jQuery 切换数据属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14482492/
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-24 16:56:39  来源:igfitidea点击:

How to toggle data attribute with jQuery?

javascriptjquery

提问by Shpigford

I need to toggle between two possible values for a data attribute.

我需要在数据属性的两个可能值之间切换。

If data-stateis equal to enabledthen I want to change it to disabledand vice versa.

如果data-state等于enabled那么我想将其更改为disabled,反之亦然。

$('.sites .state').on('ajax:success', function(data, status, xhr) {
   var site = $(this).parents('article').first();

   if (site.data('state') == 'enabled') {
     site.attr('data-state', 'disabled');
   } else {
     site.attr('data-state', 'enabled');
   }
});

NOTE: I needed to change the DOM element and to my knowledge, I can't use datato do that (hence the use of attr).

注意:我需要更改 DOM 元素,据我所知,我不能data这样做(因此使用attr)。

采纳答案by Arun P Johny

site.attr('data-state', 'disabled');

Should be

应该

site.data('state', 'disabled');

When an element is created the data-<value>attribute can be used in initialize the data property, but after that you have to use the jQuery.data()method to fetch or modify the data.

创建元素时,该data-<value>属性可用于初始化数据属性,但之后您必须使用jQuery.data()方法来获取或修改数据。

While $(el).data('<data-name>')returns the value, $(el).data('<data-name>', value)set the data value.

$(el).data('<data-name>')返回值的同时,$(el).data('<data-name>', value)设置数据值。

Updated: Based on the updated requirement

更新:基于更新的要求

$('div').attr('data-state', $('div').attr('data-state') == 'enabled' ? 'disabled' : 'enabled')

Fiddle

小提琴

回答by Mark Pieszak - Trilon.io

Not really sure what the problem is, but since you are using .data()you might as well keep using it in your if/else. Doing .attr('data-state')saves it on the DOM element itself (visible when you inspect the element), while with .data('state')it is invisible, and also faster.

不太确定问题是什么,但既然你正在使用,.data()你不妨在 if/else 中继续使用它。这样做.attr('data-state')会将它保存在 DOM 元素本身(当您检查元素时可见),而.data('state')它是不可见的,而且速度更快。

Also if you use the ternary operator you can make it into 1 small line:

此外,如果您使用三元运算符,您可以将其变成 1 条小线:

site.attr('data-state', site.data('state') === 'enabled' 
    ? 'disabled' 
    : 'enabled');

回答by Robin Maben

site.data('state', (site.data('state') == 'enabled' ? 'disabled' : 'enabled'))