Warm tip: This article is reproduced from serverfault.com, please click

javascript-我没有从表行的jQuery中通过ID获取特定值,它显示“未定义”

(javascript - I'm not getting the specific value by id in jquery from the table row, it shows 'undefined')

发布于 2020-11-28 07:34:35

单击“添加到购物车btn”时,我想从表行中捕获值。桌子在这里。

<table class="table" id="myTable">
    <thead class="thead-dark">
       <tr>
          <th scope="col">ID</th>
            <th scope="col">Name</th>
            <th scope="col">Availability</th>
            <th scope="col">Price</th>
            <th scope="col">Category</th>
            <th scope="col">Type</th>
            <th scope="col">Vendor</th>
            <th scope="col">Handle</th>
           </tr>
      </thead>
      <tbody>

    <% for(var i=0; i < medicines.length; i++) { %>
      <tr>
         <th scope="row"><span id="id"><%= medicines[i].id %></span></th>
         <td><%= medicines[i].name %></td>
         <td><%= medicines[i].availability %></td>
         <td><%= medicines[i].price %></td>
         <td><%= medicines[i].category %></td>
         <td><%= medicines[i].type %></td>
       <td><%= medicines[i].vendor %></td>
         <td>
            <input type="number" id="availability" name="quantity" min="1" max="<%= medicines[i].availability %>" required>
                                               
            <input type="submit" id="btn" class="btn btn-secondary" value="Add to Cart">
         </td>
     </tr>
    <% } %>
                              
  </tbody>
</table>

和jQuery代码是...

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


<script>
$(document).ready(() => {
            
    $("#myTable").on('click', '#btn', () => {
        var row = $(this).closest("tr");

        var col = row.find("#id").html();
        alert(col);
    });
            
});
</script>

我应该获得我单击的行的特定列的值。但是在警报中它显示未定义!

如何从我单击表的行中获取id =“ id”的值?

更新:当我在click事件中使用function(){}而不是()=> {}箭头函数时,它起作用了!

Questioner
Saqib
Viewed
0
Saqib 2020-11-29 00:01:48

当我将代码更改为下面的代码时,它可以正常工作。我意识到,箭头功能对我不起作用!

<script>
$(document).ready(function() {
   $("#btn").click(function() {
        
        var row = $(this).closest("tr");

        var col = row.find("#id").text();
        alert(col);
    });
});
</script>