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

循环获取元素属性值:遍历指定类按钮获取price属性并判断

Fixing Your Button Loop to Check Price Attributes

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:

  1. Incorrect selector: $("see") tries to find <see> HTML tags, not elements with the see class. You need to use $(".see") (the dot targets classes).
  2. While loop isn't built for iteration: A while loop here would just keep checking the first button's price attribute 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:33:23