在HTML中自定义数据属性
The "data-" global attributes in HTML are used to store custom data private to the page or application. They provide a way to store extra information on HTML elements that JavaScript can later access. The "data-" attributes consist of a name (data-*) and a value. The name should be in lowercase and contain a hyphen (-) to separate words.
Here's how to use "data-*" attributes in HTML:
Add a "data-*" attribute to an HTML element:
<div id="example" data-custom-info="This is custom data.">My custom element</div>In this example, we've added a "data-custom-info" attribute to the
<div>element with the value "This is custom data."Access the "data-*" attribute value using JavaScript:
<script> // Access the element with the data-* attribute var element = document.getElementById('example'); // Get the value of the data-custom-info attribute var customInfo = element.getAttribute('data-custom-info'); console.log(customInfo); // Output: This is custom data. </script>In this script, we access the
<div>element with the data-custom-info attribute and then use thegetAttribute()method to retrieve the value of the attribute.Alternatively, you can use the
datasetproperty to access "data-*" attributes in JavaScript:<script> // Access the element with the data-* attribute var element = document.getElementById('example'); // Get the value of the data-custom-info attribute using the dataset property var customInfo = element.dataset.customInfo; console.log(customInfo); // Output: This is custom data. </script>In this example, we use the
datasetproperty to access the "data-custom-info" attribute. Note that when usingdataset, you should remove the "data-" prefix and convert the remaining name to camelCase.Access the "data-*" attribute value using jQuery
var customInfo = $('#example').attr('data-custom-info');
You can use "data-*" attributes in various scenarios, such as storing additional information for an element, passing data to JavaScript functions or event handlers, or adding custom data to elements for use in CSS selectors.
参考资料:
Using data attributes with JQuery
Answer by ChatGPT-4
评论已关闭