You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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, the data-url values).
  • .get(): Converts the jQuery object into a standard JavaScript array, making it easier to work with (like using forEach or joining into a string).
  • .data('url'): Retrieves the value of the data-url attribute. If you're dynamically updating the data-url attribute 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 the answerPick class 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:24:09