When working with the jQuery Quicksand plugin, it's often necessary to retrieve the 'data-id' attribute of clicked elements to pass information to various web services. Here's how to effectively obtain this attribute value:
The 'data-id' attribute can be accessed using the .attr() method in jQuery. The syntax is as follows:
$(this).attr("data-id")
This expression returns the value of the 'data-id' attribute as a string.
For example, if the clicked element has the following HTML:
<li data-id="id-40">...</li>
The following jQuery code will retrieve the 'data-id' attribute:
$("#list li").on('click', function() { // Get the data-id value var dataId = $(this).attr("data-id"); // Use the dataId value as needed });
Alternatively, you can use the .data() method for jQuery versions 1.4.3 and above. The .data() method returns the 'data-id' value as a native JavaScript type (e.g., number, boolean) rather than a string.
$(this).data("id")
Remember, when using the .data() method, the part after 'data-' must be lowercase. For instance, 'data-idNum' will fail, while 'data-idnum' will succeed.
The above is the detailed content of How to Retrieve a `data-id` Attribute Value Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!