Home >Web Front-end >JS Tutorial >How Can I Retrieve the `data-id` Attribute of Clicked Items Using jQuery Quicksand?

How Can I Retrieve the `data-id` Attribute of Clicked Items Using jQuery Quicksand?

Susan Sarandon
Susan SarandonOriginal
2024-12-28 11:58:10425browse

How Can I Retrieve the `data-id` Attribute of Clicked Items Using jQuery Quicksand?

Retrieving the Data-id Attribute for Clicked Items in 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.

Obtaining the Data-id Attribute

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")

Example Implementation

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn