如何使用jQuery获取幻灯片分页组件的data-current值?
data-current Value Using jQuery Getting the data-current value from your pagination container is straightforward with jQuery. Here are the most reliable ways to do it, depending on how your pagination script updates the value:
1. Get the Parsed Numeric Value (Recommended for Initial Load)
If you just need the initial value (or if your script uses jQuery's .data() method to update it), use the .data() method. jQuery automatically parses numeric data-* attributes into number types:
// Select the pagination container and get the current page number const currentPage = $('#data-total').data('current'); console.log(currentPage); // Outputs: 4 (as a number)
2. Get the Raw DOM Attribute Value (Best for Updated Values)
If your pagination script updates the data-current attribute directly in the HTML (e.g., changing it via setAttribute or jQuery's .attr()), use .attr() to fetch the latest visible value from the DOM. This avoids any caching issues with jQuery's internal data store:
// Get the latest data-current value from the DOM const currentPage = $('#data-total').attr('data-current'); console.log(currentPage); // Outputs: "4" (as a string; convert to number with parseInt() if needed)
3. Get the Value After a Page Click
To capture the updated data-current value immediately after a user clicks a page, attach a click event listener to the page items and fetch the value inside the handler:
// Listen for clicks on pagination pages $('.page').on('click', function() { // Wait a tiny moment for the pagination script to update the attribute setTimeout(() => { const updatedCurrentPage = $('#data-total').attr('data-current'); console.log('Updated current page:', updatedCurrentPage); }, 10); });
The small setTimeout ensures the pagination script has time to update the data-current attribute before we fetch it. If your pagination uses a callback after updating, you can skip the timeout and place the code inside that callback instead.
内容的提问来源于stack exchange,提问作者Ashok Charu

