【问题标题】:How do I access only specific elements that have a same class? jquery如何仅访问具有相同类的特定元素? jQuery
【发布时间】:2021-03-11 09:47:08
【问题描述】:

我正在尝试创建一个类似购物车的功能,该功能显示在数据库中找到的产品,用户可以选择每种产品的数量,然后将其添加到购物车中。我目前面临的问题是,当用户点击加号按钮时,所有数量都会发生变化,它们都会显示点击的总价。 这是我的代码:

$('.plus').bind('click', function(e) {
  $('.minus').prop('disabled', false)

  var quantity = parseInt($('.quantity').val());
  if (!isNaN(quantity) && quantity < 8) {
    $('.quantity').val(quantity + 1);
  } else if (quantity == 8) {
    $('.quantity').val(9);
    $(this).prop('disabled', true)
  }
  var price = parseFloat($('.price').text()).toFixed(2);

  if (quantity != 9) {
    if ((price * quantity) % 1 !== 0) {
      $(".total_price").val(parseFloat(price * (quantity + 1)) + ".00");
    } else {
      $(".total_price").val(parseFloat(price * (quantity + 1)) + "0");
    }
    $(".total_price").css("font-weight", "Bold");
    $(".total_price").css("color", "brown");
  } else {
    if ((price * quantity) % 1 !== 0) {
      $(".total_price").val(parseFloat(price * 9) + ".00");
    } else {
      $(".total_price").val(parseFloat(price * 9) + "0");
    }
    $(".total_price").css("font-weight", "Bold");
    $(".total_price").css("color", "brown");
  }
});

$('.minus').bind('click', function(e) {
  $('.plus').prop('disabled', false)

  var quantity = parseInt($('.quantity').val());
  if (!isNaN(quantity) && quantity > 1) {
    $('.quantity').val(quantity - 1);
  } else {
    $(this).prop('disabled', true)
    $('.quantity').val(0);

  }
  var price = parseFloat($('.price').text()).toFixed(2);
  if ((price * quantity) % 1 !== 0) {
    $(".total_price").val(parseFloat(price * (quantity - 1)) + ".00");
  } else {
    $(".total_price").val(parseFloat(price * (quantity - 1)) + "0");
  }

  if (quantity != 1) {
    $(".total_price").css("font-weight", "Bold");
    $(".total_price").css("color", "brown");
  } else {

    $(".total_price").css("font-weight", "normal");
    $(".total_price").css("color", "black");
  }


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='row' id='product_item'>
  <div class='col-5' style='margin: auto;'>
    <input class='product_name' readonly type='text' name='product_name' style='display: inline; width:100%; border:white;' value='".$row[' productName ']."'>
  </div>
  <div class='col-1' style='margin: auto;'>
    <div class='price' style='display: inline;'>".$row['price']."</div>€</div>

  <div class='col-3' style='display:inline;  margin: auto;'>
    <div class='input_group_button'>
      <button class='btn plus' type='button'>
           <img src='img/plus.png'>
       </button>
    </div>
    <input class='input_group_field quantity' readonly type='number' name='quantity' value='0' max=9>
    <div class='input_group_button'>
      <button class='btn minus' type='button'>
         <img src='img/minus.png'>
      </button>
    </div>
  </div>
  <div class='col-2' style='margin: auto;'><input class='total_price' readonly type='number' name='total_price' style='display: inline; width:65%; border:white;' value='0.00'>€</div>
  <div class='col-1'>
    <button class='btn' type='button' id='add_cart'>
     <img src='img/add-to-cart.png'>
    </button>
  </div>
</div>

感谢我能得到的任何帮助!

【问题讨论】:

  • 制作结构良好的标记,您可以使用它来依赖元素的顺序。然后使用event对象传递给handler函数,从event.target获取点击的元素,并使用HTML结构遍历想要的元素,如target.prev()、target.parent().prev等得到想要处理的元素。

标签: javascript html jquery class


【解决方案1】:

我已经以你的例子并整理了一些可能对你有用的东西,这里是 JSFiddle 可以自己测试它

https://jsfiddle.net/xsvg7t8L/

这里是 HTML,而不是我如何为每个数量字段添加一个 ID,然后为加号和减号按钮添加一个属性,这是我们要更新的字段的选择器。

<div class='row' id='product_item'>
    <input id="quantity_1" class='input_group_field quantity' readonly type='number' name='quantity_1' value='0' max=9>
      <button class='btn plus' type='button' update="#quantity_1">
        +
      </button>
      <button class='btn minus' type='button' update="#quantity_1">
        -
      </button>
    </div>
<div class='row' id='product_item_2'>
      <input id="quantity_2" class='input_group_field quantity' readonly type='number' name='quantity' value='0' max=9>
      <button class='btn plus' type='button' update="#quantity_2">
        +
      </button>
      <button class='btn minus' type='button' update="#quantity_2">
        -
      </button>
</div>

这是 JS,你可以看到我使用 jQuery 的 attr() 函数获取属性,然后使用它来获取指向数量字段的指针,而不是使用类。

$('.plus').bind('click', function(e) {
  $('.minus').prop('disabled', false)
    // This attribute will contain the ID of the quantity you want to update
  var qtyField = $(this).attr('update');
  var quantity = parseInt($(qtyField).val());
  if (!isNaN(quantity) && quantity < 8) {
    $(qtyField).val(quantity + 1);
  } else if (quantity == 8) {
    $(qtyField).val(9);
    $(this).prop('disabled', true)
  }
});

$('.minus').bind('click', function(e) {
  $('.plus').prop('disabled', false)
  // This attribute will contain the ID of the quantity you want to update
  var qtyField = $(this).attr('update');
  var quantity = parseInt($(qtyField).val());
  if (!isNaN(quantity) && quantity > 1) {
    $(qtyField).val(quantity - 1);
  } else {
    $(this).prop('disabled', true)
    $(qtyField).val(0);
  }
});

不完全符合您的要求,但希望对您有所帮助!

【讨论】:

  • 请澄清您为什么认为该陈述是错误的?使用最接近()和其他类似的方法很好,但是找到的元素完全取决于标记的布局,所以不是我将其归类为“查找特定元素”的内容,虽然它纯粹是一种技术性,并且可以解释并在您的示例按预期工作(顺便说一句很好的答案)。对我来说问题是,如果标记发生变化,如果您没有同时审查和更新 JS,则可能会引入错误,如果您使用 ID,则可以减少出现此问题的可能性。
  • 我同意这一点 - 我的观点是,您关于唯一标识元素的第一个声明是 only 这样做的方法是不正确的。如果您删除该行,我将很乐意删除反对票,因为答案本身具有优点,尽管我建议使用 data-update 而不是创建非标准属性。
  • 我已经删除了该评论,事后看来,我可以看到如果没有进一步解释,阅读它的人可能会感到困惑,这实际上是我在这里发布的第一个答案,所以它适合我肯定会继续工作,感谢您的反馈!是的,关于使用该属性的好建议。
【解决方案2】:

要完成这项工作,您可以使用对单击元素的引用,在事件处理程序中使用 this 关键字,使用 jQuery 的内置方法(例如 closest() 和 @987654323)遍历 DOM 以查找相关元素@。

此外,还有一些其他的事情可以解决。

  • bind() 已被弃用。请改用on()
  • 您可以组合.minus.plus 事件处理程序,方法是使用按钮上的data 属性来确定应将哪个值添加到数量。这减少了代码中的重复次数。
  • 您可以使用Math.max()Math.min() 设置数量字段的范围。通过消除对冗长的 if 条件的需求,这使代码更加简洁。
  • 不要在整个页面中重复的内容中使用id 属性。 id 必须在 DOM 中是唯一的。改用class 属性按行为对元素进行分组。
  • 使用块级div 元素并强制它内联是很奇怪的。如果您想直接使用内联元素,例如 span
  • 避免在 HTML 中添加样式规则。将它们放在外部样式表中。

说了这么多,试试这个:

$('.btn-inc').on('click', function(e) {
  let $el = $(this);
  let inc = $el.data('inc');
  $el.closest('.col-3').find('.quantity').val((i, v) => Math.min(Math.max(parseInt(v, 10) + inc, 0), 8));
  updatePrice();
});

let updatePrice = () => {
  $('.row').each((i, row) => {
    let $row = $(row);
    let $price = $row.find('.price');
    let $quantity = $row.find('.quantity');

    $row.find('.total_price').val(parseFloat($price.text() * $quantity.val()).toFixed(2));
  });
}
.row {
  border: 1px solid #CCC;
  border-radius: 5px;
  margin: 10px;
  padding: 10px;
} 
.row > div margin: auto;

}
.row > .col-3 {
  display: inline;
}
input.product_name {
  display: inline;
  width: 100%;
  border: white;
}
input.total_price {
  display: inline;
  width: 65%;
  border: white;
}
span.price {
  display: inline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- item 1 -->
<div class="row">
  <div class="col-5">
    <input class="product_name" readonly type="text" name="product_name" value="productName">
  </div>
  <div class="col-1">
    <span class="price">1.00</span>€
  </div>
  <div class="col-3">
    <div class="input_group_button">
      <button class="btn plus btn-inc" type="button" data-inc="1">+</button>
    </div>
    <input class="input_group_field quantity" readonly type="number" name="quantity" value="0" max="9">
    <div class="input_group_button">
      <button class="btn minus btn-inc" type="button" data-inc="-1">-</button>
    </div>
  </div>
  <div class="col-2">
    <input class="total_price" readonly type="number" name="total_price" value="0.00"> €
  </div>
  <div class="col-1">
    <button class="btn" type="button" class="add_cart">Add to cart</button>
  </div>
</div>

<!-- item 2 -->
<div class="row">
  <div class="col-5">
    <input class="product_name" readonly type="text" name="product_name" value="productName">
  </div>
  <div class="col-1">
    <span class="price">9.99</span>€
  </div>
  <div class="col-3">
    <div class="input_group_button">
      <button class="btn plus btn-inc" type="button" data-inc="1">+</button>
    </div>
    <input class="input_group_field quantity" readonly type="number" name="quantity" value="0" max="9">
    <div class="input_group_button">
      <button class="btn minus btn-inc" type="button" data-inc="-1">-</button>
    </div>
  </div>
  <div class="col-2">
    <input class="total_price" readonly type="number" name="total_price" value="0.00"> €
  </div>
  <div class="col-1">
    <button class="btn" type="button" class="add_cart">Add to cart</button>
  </div>
</div>

【讨论】:

  • 你太棒了!谢谢你把一切都说得这么清楚!!!
  • 没问题,很高兴为您提供帮助
【解决方案3】:

你做错了。

想想看,你有一个product_item 的列表,然后当你点击加号或减号时,你需要那些在这个特定的product_item 下的值,对吧?

好的,让我们看看我们可以对您的代码做些什么,并进行一些小的更改来解决问题。

$('.plus').bind('click', function(e) {
  var productItem = $(this).closest("#product_item")
  console.log(productItem.length)
  productItem.find('.minus').prop('disabled', false)
  var quantity = parseInt(productItem.find('.quantity').val());
  if (!isNaN(quantity) && quantity < 8) {
    productItem.find('.quantity').val(quantity + 1);
  } else if (quantity == 8) {
    productItem.find('.quantity').val(9);
    $(this).prop('disabled', true)
  }
  var price = parseFloat(productItem.find('.price').text()).toFixed(2);

  if (quantity != 9) {
    if ((price * quantity) % 1 !== 0) {
      productItem.find(".total_price").val(parseFloat(price * (quantity + 1)) + ".00");
    } else {
      productItem.find(".total_price").val(parseFloat(price * (quantity + 1)) + "0");
    }
    productItem.find(".total_price").css("font-weight", "Bold");
    productItem.find(".total_price").css("color", "brown");
  } else {
    if ((price * quantity) % 1 !== 0) {
      productItem.find(".total_price").val(parseFloat(price * 9) + ".00");
    } else {
      productItem.find(".total_price").val(parseFloat(price * 9) + "0");
    }
    productItem.find(".total_price").css("font-weight", "Bold");
    productItem.find(".total_price").css("color", "brown");
  }
});

$('.minus').bind('click', function(e) {

  var productItem = $(this).closest("#product_item")
  productItem.find('.plus').prop('disabled', false)
  var quantity = parseInt(productItem.find('.quantity').val());
  if (!isNaN(quantity) && quantity > 1) {
    productItem.find('.quantity').val(quantity - 1);
  } else {
    $(this).prop('disabled', true)
    productItem.find('.quantity').val(0);

  }
  var price = parseFloat(productItem.find('.price').text()).toFixed(2);
  if ((price * quantity) % 1 !== 0) {
    productItem.find(".total_price").val(parseFloat(price * (quantity - 1)) + ".00");
  } else {
    productItem.find(".total_price").val(parseFloat(price * (quantity - 1)) + "0");
  }

  if (quantity != 1) {
    productItem.find(".total_price").css("font-weight", "Bold");
    productItem.find(".total_price").css("color", "brown");
  } else {

    productItem.find(".total_price").css("font-weight", "normal");
    productItem.find(".total_price").css("color", "black");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='row' id='product_item'>
  <div class='col-5' style='margin: auto;'>
    <input class='product_name' readonly type='text' name='product_name' style='display: inline; width:100%; border:white;' value='".$row[' productName ']."'>
  </div>
  <div class='col-1' style='margin: auto;'>
    <div class='price' style='display: inline;'>".$row['price']."</div>€</div>

  <div class='col-3' style='display:inline;  margin: auto;'>
    <div class='input_group_button'>
      <button class='btn plus' type='button'>
           <img src='img/plus.png'>
       </button>
    </div>
    <input class='input_group_field quantity' readonly type='number' name='quantity' value='0' max=9>
    <div class='input_group_button'>
      <button class='btn minus' type='button'>
         <img src='img/minus.png'>
      </button>
    </div>
  </div>
  <div class='col-2' style='margin: auto;'><input class='total_price' readonly type='number' name='total_price' style='display: inline; width:65%; border:white;' value='0.00'>€</div>
  <div class='col-1'>
    <button class='btn' type='button' id='add_cart'>
     <img src='img/add-to-cart.png'>
    </button>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2021-07-18
    • 1970-01-01
    • 2022-10-07
    • 2019-11-26
    • 2011-06-12
    • 1970-01-01
    • 2020-07-12
    • 2012-02-28
    • 2014-07-12
    相关资源
    最近更新 更多