2016-11-04 68 views
1

所以我有这个html代码和jQuery代码。当我按下带有类别名称“fa-products”的tablerows“produkter”按钮时,我想要找到与您选择单击的按钮位于同一表格上的隐藏字段输入(每个tablerow都有一个隐藏字段输入和一个“产品按钮”)。那么我想将隐藏字段的值保存在一个变量中,任何人都可以帮助我?当我“console.log(discountId);”它响应undefiendjquery中的“nearest()”方法不会工作

<div class="eastSide row top-buffer col-xs-8" style="overflow:scroll; height:250px;"> 

    <table style="width:100%"> 
     <tr> 
      <th>Code</th> 
      <th>Aktiv</th> 
      <th>Skapad</th> 
      <th></th> 
     </tr> 
     @foreach (var discount in Model.DiscountList) 
     { 

      <tr> 

       <td><input name="codeTextBox" id="codeTextBox" value="@discount.Code" maxlength="18" /></td> 

       <td><input type="checkbox" id="activeCheckBox" name="activeCheckBox" checked="@discount.Active" /></td> 
       <td><input type="datetime" value="@discount.CreatedDate" readonly /></td> 
       <td> 
        <input type="button" value="Radera" class="fa fa-remove" data-url="@Url.Action("DeleteDiscountCode","Discount",new { id= discount.Id})" /> 
        <input type="button" value="Uppdatera" class="fa fa-update" data-url="@Url.Action("UpdateDiscount","Discount")" /> 
        <input type="button" value="Produkter" class="fa fa-products" id="@discount.Id" data-url="@Url.Action("chooseProductsForDiscountCode","Discount")" /> 
       </td> 
       <td><input id="id" type="hidden" value="@discount.Id" /></td> 
      </tr> 
     } 
    </table> 


</div> 



<script> 
$(".fa-products").on("click", function (e) { 


       var discountId =  $(event.target).closest('input[type="hidden"]').val(); 
       console.log(discountId); 





      }); 
</script> 
+0

当我CONSOLE.LOG(discountId) ;它响应undefiend @Teemu –

+0

[最接近的文档说明](http://api.jquery.com/closest/):“_...通过测试元素本身并遍历起来,获得匹配选择器的第一个元素通过它的祖先......“,你的”隐藏的“并不是一帆风顺的。 – Teemu

回答

4

它不会工作,因为隐藏的输入不是注册元素的父项。

也许这将解决您的问题:$(event.target).closest('tr').find('input[type="hidden"]').val();

+2

这应该是一个评论,而不是答案 – Dekel

+0

你是对的,我编辑了答案 – ltamajs

+0

现在,它是更好的:) – Dekel

0

你需要通过closest做搜索共同的父元素,然后找到input结果内:

$(".fa-products").on("click", function (e) { 
    var discountId = $(event.target).closest('tr').find('input[type="hidden"]').val(); 
    console.log(discountId); 
});