Home >Web Front-end >JS Tutorial >How Can I Retrieve the `data-id` Attribute of Clicked Items Using jQuery Quicksand?
When working with the jQuery Quicksand plugin, obtaining the data-id attribute of clicked elements is essential for passing it to web services or performing further actions. This article aims to provide a comprehensive solution to this requirement.
The Quicksand plugin allows you to sort or filter elements dynamically without reloading the page. To bind click events to the sorted or filtered elements, the .on() method is employed. However, it becomes necessary to access the data-id attribute to retrieve specific information associated with the clicked element.
To retrieve the data-id attribute value, jQuery offers two methods:
Using .attr():
This method directly retrieves the attribute value as a string.
$(this).attr("data-id")
Using .data():
Released in jQuery 1.4.3, this method retrieves the attribute value as a parsed data type (if possible).
$(this).data("id")
Consider the following HTML and JavaScript code:
<ul>
$("#list li").on('click', function() { let dataId = $(this).attr("data-id") || $(this).data("id"); alert(dataId); });
In this example, the data-id attribute's value can be accessed using the .attr() or .data() method depending on the jQuery version used. When the element with data-id="id-40" is clicked, an alert dialog will display the value.
The above is the detailed content of How Can I Retrieve the `data-id` Attribute of Clicked Items Using jQuery Quicksand?. For more information, please follow other related articles on the PHP Chinese website!