Home >Web Front-end >Front-end Q&A >How to modify data-options in jquery
In jquery, you can use the attr() method to modify the "data-options" attribute. This method can set or return the attributes and values of the specified element. This attribute is used to store the private properties of the page or application. Define data, the syntax is "element object.attr("data-options", "selected:false")".
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
Html5 data-* attribute definition and usage:
data-* attributes are used to store private custom data of a page or application.
data-* attributes give us the ability to embed custom data attributes on all HTML elements.
The stored (custom) data can be leveraged within the page's JavaScript to create a better user experience (without making Ajax calls or server-side database queries).
data-* The attribute consists of two parts:
The attribute name should not contain any uppercase letters, and there must be at least one character after the prefix "data-"
The attribute value It can be any string
Modification method:
jquery:
$div.attr("data-options", "selected:false");
attr() method sets or returns the attributes and values of the selected element.
When this method is used to return an attribute value, the value of the first matching element is returned.
When this method is used to set attribute values, one or more attribute/value pairs are set for the matching element.
The syntax is
Return the value of the attribute:
$(selector).attr(attribute)
Set the attribute and value:
$(selector).attr(attribute,value)
Expand knowledge:
1. Use the getAttribute setAttribute method
div.setAttribute('data-options',{/*数据*/}); div.getAttribute("data-options");
2. Use the dataset attribute to return a collection
div.dataset --> DOMStringMap { options:"{\"name\":\"John\"}", hidden:"true", lastValue:"43"}
Can access, add, delete
div.dataset.hidden div.dataset.newAttr = "123" delete div.dataset.hidden
3. Use jquery's data method
.data( key, value ) .data( key, value ) .data( obj ) --> 设置多个键值对 .data( key ) .data( key ) .data() -->返回一个集合
What's special about jQuery is that it automatically converts the return value string into the corresponding data type.
For example, $("div").data() above --> {options : {"name":"John"}, hidden: true, lastValue: 43 }
Note: For the dataset attribute and jQuery's data method: If the data- attribute name contains a hyphen, for example: data-last-value, the hyphen will be removed and converted to camel case naming. The previous attribute name should be converted is: lastValue.
Video tutorial recommendation: jQuery video tutorial
The above is the detailed content of How to modify data-options in jquery. For more information, please follow other related articles on the PHP Chinese website!