jQuery 如何在 HTML 元素中设置数据属性

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

How to set data attributes in HTML elements

jqueryhtmlcustom-data-attribute

提问by Pulkit Mittal

I have a div with an attribute data-myval = "10". I want to update its value; wouldn't it change if I use div.data('myval',20)? Do I need to use div.attr('data-myval','20')only?

我有一个带有属性的 div data-myval = "10"。我想更新它的值;如果我使用它不会改变div.data('myval',20)吗?我div.attr('data-myval','20')只需要使用吗?

Am I getting confused between HTML5 and jQuery? Please advise. Thanks!

我对 HTML5 和 jQuery 感到困惑吗?请指教。谢谢!

EDIT: Updated div.data('myval')=20to div.data('myval',20), but still the HTML is not updating.

编辑:已更新div.data('myval')=20div.data('myval',20),但 HTML 仍未更新。

回答by Jashwant

HTML

HTML

<div id="mydiv" data-myval="10"></div>

JS

JS

var a = $('#mydiv').data('myval'); //getter

$('#mydiv').data('myval',20); //setter

Demo

演示

Reference

参考

From the reference:

从参考:

jQuery itself uses the .data()method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.

jQuery 本身使用该.data()方法将信息保存在名称 'events' 和 'handle' 下,并且还保留任何以下划线 ('_') 开头的数据名称供内部使用。

It should be noted that jQuery's data()doesn't change the dataattribute in HTML.

应该注意的是,jQuerydata()不会更改dataHTML 中的属性。

So, if you need to change the dataattribute in HTML, you should use .attr()instead.

因此,如果您需要更改dataHTML 中的属性,则应.attr()改为使用。

HTML

HTML

<div id="outer">
    <div id="mydiv" data-myval="10"></div>
</div>

?JS:

?JS:

alert($('#outer').html());   // alerts <div id="mydiv" data-myval="10"> </div>
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());   //alerts <div id="mydiv" data-myval="20"> </div>

See this demo

这个演示

回答by Baqer Naqvi

You can also use the following attrthing;

您还可以使用以下attr内容;

HTML

HTML

<div id="mydiv" data-myval="JohnCena"></div>

Script

脚本

 $('#mydiv').attr('data-myval', 'Undertaker'); // sets 
 $('#mydiv').attr('data-myval'); // gets

OR

或者

$('#mydiv').data('myval'); // gets value
$('#mydiv').data('myval','John Cena'); // sets value

回答by Johann Echavarria

Please take note that jQuery .data()is not updated when you change html5 data-attributes with javascript.

请注意,.data()当您data-使用 javascript更改 html5属性时,jQuery不会更新。

If you use jQuery .data()to set data-attributes in HTML elements you better use jQuery .data()to read them. Otherwise there can be inconsistencies if you update the attributes dynamically. For example, see setAttribute(), dataset(), attr()below. Change the value, push the button several times and see the console.

如果您使用 jQuery在 HTML 元素中.data()设置data-属性,则最好使用 jQuery.data()来读取它们。否则,如果动态更新属性,可能会出现不一致。例如,请参见下面的setAttribute()dataset()attr()。更改值,多次按下按钮并查看控制台。

$("#button").on("click", function() {
  var field = document.querySelector("#textfield")

  switch ($("#method").val()) {
    case "setAttribute":
      field.setAttribute("data-customval", field.value)
      break;
    case "dataset":
      field.dataset.customval = field.value
      break;
    case "jQuerydata":
      $(field).data("customval", field.value)
      break;
    case "jQueryattr":
      $(field).attr("data-customval", field.value)
      break;
  }

  objValues = {}
  objValues['$(field).data("customval")'] = $(field).data("customval")
  objValues['$(field).attr("data-customval")'] = $(field).attr("data-customval")
  objValues['field.getAttribute("data-customval")'] = field.getAttribute("data-customval")
  objValues['field.dataset.customval'] = field.dataset.customval

  console.table([objValues])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1>Example</h1>
<form>
  <input id="textfield" type="text" data-customval="initial">
  <br/>
  <input type="button" value="Set and show in console.table (F12)" id="button">
  <br/>
  <select id="method">
    <option value="setAttribute">setAttribute</option>
    <option value="dataset">dataset</option>
    <option value="jQuerydata">jQuery data</option>
    <option value="jQueryattr">jQuery attr</option>
  </select>
  <div id="results"></div>
</form>

回答by rajesh kakawat

Vanilla Javascript solution

原生 Javascript 解决方案

HTML

HTML

<div id="mydiv" data-myval="10"></div>

JavaScript:

JavaScript:

  • Using DOM's getAttribute()property

     var brand = mydiv.getAttribute("data-myval")//returns "10"
     mydiv.setAttribute("data-myval", "20")      //changes "data-myval" to "20"
     mydiv.removeAttribute("data-myval")         //removes "data-myval" attribute entirely
    
  • Using JavaScript's datasetproperty

    var myval = mydiv.dataset.myval     //returns "10"
    mydiv.dataset.myval = '20'          //changes "data-myval" to "20"
    mydiv.dataset.myval = null          //removes "data-myval" attribute
    
  • 使用 DOM 的getAttribute()属性

     var brand = mydiv.getAttribute("data-myval")//returns "10"
     mydiv.setAttribute("data-myval", "20")      //changes "data-myval" to "20"
     mydiv.removeAttribute("data-myval")         //removes "data-myval" attribute entirely
    
  • 使用 JavaScript 的dataset属性

    var myval = mydiv.dataset.myval     //returns "10"
    mydiv.dataset.myval = '20'          //changes "data-myval" to "20"
    mydiv.dataset.myval = null          //removes "data-myval" attribute
    

回答by Blender

If you're using jQuery, use .data():

如果您使用 jQuery,请使用.data()

div.data('myval', 20);

You can store arbitrary data with .data(), but you're restricted to just strings when using .attr().

您可以使用 存储任意数据.data(),但使用 时仅限于字符串.attr()

回答by Cody

[jQuery] .data() vs .attr() vs .extend()

[jQuery] .data() vs .attr() vs .extend()

The jQuery method .data()updates an internal object managed by jQuery through the use of the method, if I'm correct.

jQuery 方法.data()通过使用jQuery 方法更新由 jQuery 管理的内部对象,如果我是正确的。

If you'd like to update your data-attributeswith some spread, use --

如果你想data-attributes用一些点差更新你的,请使用——

$('body').attr({ 'data-test': 'text' });

-- otherwise, $('body').attr('data-test', 'text');will work just fine.

- 否则,$('body').attr('data-test', 'text');将工作得很好。

Another way you could accomplish this is using --

您可以实现此目的的另一种方法是使用-

$.extend( $('body')[0].dataset, { datum: true } );

-- which restricts any attribute change to HTMLElement.prototype.dataset, not any additional HTMLElement.prototype.attributes.

- 将任何属性更改限制为HTMLElement.prototype.dataset而不是任何额外的HTMLElement.prototype.attributes

回答by CloudBranch

Another way to set the data- attribute is using the datasetproperty.

另一种设置 data- 属性的方法是使用dataset属性。

<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>

const el = document.querySelector('#user');

// el.id == 'user'
// el.dataset.id === '1234567890'
// el.dataset.user === 'johndoe'
// el.dataset.dateOfBirth === ''

// set the data attribute
el.dataset.dateOfBirth = '1960-10-03'; 
// Result: el.dataset.dateOfBirth === 1960-10-03

delete el.dataset.dateOfBirth;
// Result: el.dataset.dateOfBirth === undefined

// 'someDataAttr' in el.dataset === false
el.dataset.someDataAttr = 'mydata';
// Result: 'someDataAttr' in el.dataset === true

回答by J. McNerney

To keep jQuery and the DOM in sync, a simple option may be

为了保持 jQuery 和 DOM 同步,一个简单的选择可能是

$('#mydiv').data('myval',20).attr('data-myval',20);