如何通过ul的id读取li列表的数据?
Got it, let's break down how to pull data from that ul#restaurant-rate star list. Below are practical, easy-to-implement methods using both vanilla JavaScript and jQuery, depending on what you're working with:
1. Vanilla JavaScript (No External Libraries)
Grab all <li> elements in the list
First, target the parent <ul> by its ID, then fetch all child <li> items:
// Get the parent ul element const rateList = document.getElementById('restaurant-rate'); // Fetch all li elements inside it const allLiItems = rateList.querySelectorAll('li');
Get all data-interest values from the stars
If you need to collect the data-interest attribute from every star:
// Convert NodeList to array, then map to get each interest value const interestValues = Array.from(allLiItems).map(li => { const starSpan = li.querySelector('.star-item'); return starSpan.dataset.interest; }); console.log(interestValues); // Outputs ["1", "2", "3", ...]
Get the data-interest value of the selected star
If you only care about the star marked with the selected class:
const selectedStar = rateList.querySelector('.star-item.selected'); if (selectedStar) { const selectedInterest = selectedStar.dataset.interest; console.log('Selected star rating:', selectedInterest); }
2. jQuery (If Your Project Uses It)
jQuery simplifies DOM manipulation, so here's how to handle the same tasks with it:
Grab all <li> elements
const allLiItems = $('#restaurant-rate li');
Get all data-interest values
// Map over each star, pull the data, then convert to an array const interestValues = $('#restaurant-rate .star-item').map(function() { return $(this).data('interest'); }).get(); console.log(interestValues); // Outputs [1, 2, 3, ...] (jQuery auto-converts data types)
Get the selected star's data-interest value
const selectedInterest = $('#restaurant-rate .star-item.selected').data('interest'); console.log('Selected star rating:', selectedInterest);
Bonus: Listen for star clicks and get data
If you want to capture data when a user clicks a star, here's how to set that up:
Vanilla JS version
rateList.addEventListener('click', function(e) { // Find the closest star span from the clicked element const starSpan = e.target.closest('.star-item'); if (starSpan) { const clickedInterest = starSpan.dataset.interest; console.log('Clicked star rating:', clickedInterest); // Optional: Update selected state document.querySelectorAll('.star-item').forEach(star => star.classList.remove('selected')); starSpan.classList.add('selected'); } });
jQuery version
$('#restaurant-rate').on('click', '.star-item', function() { const clickedInterest = $(this).data('interest'); console.log('Clicked star rating:', clickedInterest); // Optional: Update selected state $('.star-item').removeClass('selected'); $(this).addClass('selected'); });
内容的提问来源于stack exchange,提问作者Manju
相关产品推荐
相关产品推荐

