【发布时间】:2021-03-10 19:58:57
【问题描述】:
单击添加到购物车 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" 的值?
更新:当我在点击事件中使用 function() {} 而不是 () => {} 箭头函数时,它起作用了!
【问题讨论】:
-
技术上不允许在 DOM 中拥有多个具有相同 ID 的元素,您将拥有这些元素。这在实践中通常不是问题,但也许你已经找到了一个问题。使用类而不是 ID。
-
@Saqib,有没有适合您的解决方案?
-
@ShahnawazHossan 是的,我使用了不起作用的箭头功能。相反,使用普通的 function() {},它神奇地工作。
-
@Saqib, this link 可能有助于您更好地理解常规函数和箭头函数之间的区别。对了,你可以accept the answer哪一个最适合你。
标签: javascript html jquery node.js express