循环获取元素属性值:遍历指定类按钮获取price属性并判断
Hey there! Let's get that loop working properly for all your .see buttons. Your original approach has a couple of issues we'll iron out first:
- Incorrect selector:
$("see")tries to find<see>HTML tags, not elements with theseeclass. You need to use$(".see")(the dot targets classes). - While loop isn't built for iteration: A
whileloop here would just keep checking the first button'spriceattribute forever (or until it meets a condition that breaks it), instead of looping through all buttons.
Working jQuery Solution
We'll use jQuery's .each() method to iterate over every .see button, convert the price attribute to a number (critical—since attributes return strings, adding 5 would concatenate instead of sum), and check your condition:
$(".see").each(function() { // Convert the price attribute to a number to avoid string concatenation const buttonPrice = Number($(this).attr("price")); if (buttonPrice + 5 > 10) { alert("hello"); } });
Bonus: Use HTML5 Data Attributes (Best Practice)
Instead of custom price attributes, it's better to use HTML5-compliant data-* attributes. This keeps your markup valid and makes accessing values easier (jQuery's .data() method automatically converts numbers for you):
First update your HTML:
<button class="see" data-price="5">First</button> <button class="see" data-price="8">Second</button> <button class="see" data-price="10">Third</button>
Then the simplified jQuery code:
$(".see").each(function() { // .data() automatically parses the value to a number const buttonPrice = $(this).data("price"); if (buttonPrice + 5 > 10) { alert("hello"); } });
Native JavaScript Alternative (No jQuery)
If you ever want to ditch jQuery, here's how to do it with vanilla JS:
// Get all buttons with the "see" class const seeButtons = document.querySelectorAll(".see"); // Loop through each button with forEach seeButtons.forEach(button => { const buttonPrice = Number(button.getAttribute("price")); // Or with data attributes: const buttonPrice = Number(button.dataset.price); if (buttonPrice + 5 > 10) { alert("hello"); } });
All these solutions will loop through every .see button, check if price + 5 > 10, and trigger the alert whenever that condition is met.
内容的提问来源于stack exchange,提问作者Jax Flaxx

