【问题标题】:How to get values from a hidden field that is created in forEach with different values?如何从 forEach 中创建的具有不同值的隐藏字段中获取值?
【发布时间】:2018-10-26 10:23:31
【问题描述】:

我最近一直在使用 jquery。我需要把通过forEach创建的隐藏字段的参数去掉,也就是class= "productID"下,值不一样。如何单击按钮以仅从所需的隐藏字段中获取值。

<div id="successAdded" style="color: green">
  <h3>${sessionScope.successAdded}</h3>
</div>
<c:forEach items="${sessionScope.allProducts}" var="products">
  <div class="col-md-4 fashion-grid">
    <a href="single.jsp"><img src="images/product/${products.imageName}" width="250" height="350" alt="" />
      <div class="product">
        <h3>PRODUCT NAME:</h3>
        <input type="hidden" class="productID" value="${products.id}">
        <span class="getName">${products.name}</span>
        <p>${products.size}</p>
        <p>${products.color}</p>
        <p>${products.category.name}</p>
        <p>${products.manufacturer.name}</p><br></br>
        <p><span></span>${products.price}</p>
      </div>
    </a>
    <div class="fashion-view"><span></span>
      <div class="clearfix"></div>
      <input type="button" class="addProductToCart" style="margin-top: 50%;" value="Add to cart" />
    </div>
  </div>
jQuery(document).ready(function() {
  $('.addProductToCart').on('click', function getPage() {
    var id = $(this).find('.productID').val();
    alert(id);

    $.ajax({
      type: "GET",
      url: "cart",
      data: "productID=" + id,
      success: function(page) {
        $("#header men").text(page);
        $("#productCount").text("(" + page['productCount'] + ")");
      }
    });
  });

我在我的实现中得到未定义的值

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    这里有两个问题。首先,隐藏元素上面有一个class,所以你需要在选择器前面加上.,例如。 .productID.

    其次,您使用单击按钮中的find() 来查找隐藏字段,但它不是该元素的子元素。相反,它是父母兄弟姐妹的孩子。因此,您需要组合 closest()prev()find() 来检索它,如下所示:

    jQuery(document).ready(function() {
      $('.addProductToCart').on('click', function getPage() {
        var id = $(this).closest('.fashion-view').prev('a').find('.productID').val();
        console.log(id);
    
        $.ajax({
          type: "GET",
          url: "cart",
          data: { productID:  id },
          success: function(page) {
            $("#header men").text(page);
            $("#productCount").text("(" + page['productCount'] + ")");
          }
        });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-10
      • 2015-08-12
      • 2018-10-05
      • 2010-10-20
      • 2013-04-06
      • 1970-01-01
      相关资源
      最近更新 更多