gpt4 book ai didi

javascript - 单击表格上 td 内的按钮并获取其他 td 值

转载 作者:行者123 更新时间:2023-12-03 05:39:16 24 4
gpt4 key购买 nike

我想单击 <td> 内的按钮单击时获取其他 <td> 的值位于 <tr> 内这是到目前为止的代码:

        $(document).ready(function(){
$('#main').find('tr').on("click", function() {
var customerId = $(this).find('td:eq(1)').text();
$('#texti').text(customerId);
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add new list item</button>
<p>Click the above button to dynamically add new list items. You can remove it later.</p>
<table id="main">
<tr>
<td>list item 1 </td>
<td>list item 2 </td>
<td>list item 3 </td>
<td ><input type='button' value='Update' name ='updateBox' id='updateBox' /></td>
</tr>
<tr>
<td>list item 4</td>
<td>list item 5</td>
<td>list item 6</td>
<td ><input type='button' value='Update' name ='updateBox' id='updateBox' /></td>
</tr>
<tr>
<td>list item 7</td>
<td>list item 8</td>
<td>list item 9</td>
<td ><input type='button' value='Update' name ='updateBox' id='updateBox' /></td>
</tr>
</table>
<a name="texti" id="texti"> x </a>

这段代码可以工作,但我只想要按钮来执行此操作。在我的代码中,当我单击列表项 1、列表项 2 或列表项 3 时,它们将充当按钮。我不想要这样,我想要可点击的按钮

最佳答案

您的点击事件适用于整行,因此第一步是使其仅适用于按钮:

$("#main tr input[type='button']").on("click", function() {

事件处理程序用于按钮,因此您需要向上移动到行才能获取单元格:

$("#main tr input[type='button']").on("click", function() {
var row = $(this).closest("tr");
var customerId = row.find('td:eq(1)').text();
$('#texti').text(customerId); // assume this is outside the row
});
<小时/>

作为额外的,我建议您通过给它一个类来指示哪个单元格包含您想要的数据,然后您不需要使用索引:

<tr>
<td>list item 1 </td>
<td class='data-customerid'>list item 2 </td>
<td>list item 3 </td>
<td ><input type='button' value='Update' name ='updateBox' id='updateBox' /></td>
</tr>

然后

var customerId = row.find("td.data-customer-id').text();

关于javascript - 单击表格上 td 内的按钮并获取其他 td 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40608415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com