如何使用jQuery获取问答页面中选中项的多个data-url属性值?
Collecting Selected Answer URLs with jQuery
Here's a straightforward implementation to grab all data-url values from your selected answers and use them as needed:
$(document).ready(function() { // Handle submit button click $('#submit-btn').on('click', function(e) { // Prevent default form submission if using a form e.preventDefault(); // Collect all data-url values from elements with "answerPick" class const selectedUrls = $('.answerPick').map(function() { // Use .data('url') to get the data attribute value return $(this).data('url'); }).get(); // Convert jQuery object to a regular array // Now you have an array of all selected URLs console.log('Selected URLs:', selectedUrls); // Example: Append the URLs to a target element (adjust selector as needed) const target = $('#result-container'); target.empty(); // Clear previous content selectedUrls.forEach(url => { target.append(`<p>${url}</p>`); }); }); });
Key Details:
.map(): This jQuery method loops through each matched element and returns a new jQuery object containing the values we extract (in this case, thedata-urlvalues)..get(): Converts the jQuery object into a standard JavaScript array, making it easier to work with (like usingforEachor joining into a string)..data('url'): Retrieves the value of thedata-urlattribute. If you're dynamically updating thedata-urlattribute after page load, use.attr('data-url')instead to get the current attribute value directly from the DOM.
Quick Note on Single/Multi-Select Logic
To make sure your class toggling works correctly for both modes:
- Single-select: When an
<li>is clicked, remove theanswerPickclass from all siblings first, then add it to the clicked item:$('.single-select-group li').on('click', function() { $(this).siblings().removeClass('answerPick'); $(this).toggleClass('answerPick'); }); - Multi-select: Just toggle the class on the clicked item without affecting others:
$('.multi-select-group li').on('click', function() { $(this).toggleClass('answerPick'); });
This setup ensures that only the correct answers have the answerPick class, so your submit handler will collect the right URLs every time.
内容的提问来源于stack exchange,提问作者JoeG
相关产品推荐
相关产品推荐

