如何使用 JavaScript 获取 class 中最接近函数调用的元素

How to get closest element of a class to a function call using JavaScript

问题: 我的网站上有一个简单的店面,允许用户 select 数量然后添加到购物车。我遇到的问题是当用户添加到购物车时,该函数正在获取 html 文件中的第一个 <select> <option>。结果是添加到购物车的任何项目都是按第一个 select 或数量添加的。我避免使用 id 并将它们传递给函数,因为在某些时候所有店面项目都会被动态加载。 这是我的第一次网络开发经历。

预期结果:当select输入商品的数量并添加到购物车时,数量应取决于“最近”的数量。

我的理解: 在我的 addQty(); 函数中,var e = document.getElementByClassName("qty);" 应该得到最接近函数调用的“数量”class。我不知道该怎么做。

代码:下面是一张物品卡html的样子(有多个物品卡)和我写的JS函数

*HTML

<div class="card-footer">
    <select class="qty">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
    </select>
    <button onclick="addQty();">Add to Cart</button>
</div>

JS

function addQty()
{
  var e = document.getElementClassName("qty");
  var qty = e.options[e.selectedIndex].value;
  var s =
  {
    //Reset the cart session  to remove everything added to the cart previously.
    'reset':true,
    //Define the product path(s) and the quantity to add.
    'products' : [
      {
        'path':'test-product',
        'quantity': qty
      }
    ],
    'checkout': false
  }
  fastspring.builder.push(s);
}

感谢您的帮助。

我的解决方案 我在 DOM 中为每个产品添加了一个更高的产品 ID。然后在 querySelector() 调用中使用它来确定引用了哪个 select。

<div class="column" id="test-product-2">
    <div class="card-footer">
        <select class="qty">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
        </select>
        <button onclick="addQty('test-product-2');">Add to Cart</button>
    </div>
</div>
function addQty(product_path)
{
  var selector = "#" + product_path + " .qty";
  var e = document.querySelector(selector);
  //var e = document.closest("qty");
  var qty = e.options[e.selectedIndex].value;
  var s =
  {
    //Reset the cart session  to remove everything added to the cart previously.
    'reset': false,
    //Define the product path(s) and the quantity to add.
    'products' : [
      {
        'path':product_path,
        'quantity': qty
      }
    ],
    'checkout': false
  }
  fastspring.builder.push(s);
}

您似乎正在使用 getElementById,但您尝试获取的元素没有该 ID。您应该将 id 添加到该元素或通过其他内容(例如类名)进行搜索。下面是 id 解决方案的样子:

<div class="card-footer">
    <select class="qty" id="qty">
    ...
</div>

如果您要在一个页面上有多个产品并且不想在 select 标签上放置 id,您可能仍然希望在一个页面上使用唯一 ID每个产品的 DOM 中更高级别的标签。并将该值传递给您的 addQty 函数。然后你可以使用 querySelector,像这样:

var qtySelect = document.querySelect("#uniqueId .qty");
var qty = qtySelect.options[qtySelect.selectedIndex].value;