gpt4 book ai didi

javascript - 单击按钮将值传递给 jquery 函数

转载 作者:行者123 更新时间:2023-12-03 04:37:26 27 4
gpt4 key购买 nike

我的 HTML 页面中有下表,我是 Jquery 的新手

<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Start Date</th>
<th>Severity</th>
<th>Edit Data</th>
</tr>
</thead>
<tbody id="myTable">

<tr style="display: table-row;">
<td>New Rule</td>
<td>New Rule</td>
<td>2017-04-04</td>
<td>High</td>
<td>
<button class="btn btn-primary btn-sm editBtn">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
Edit
</button>
<button onclick="window.location =&quot;/EmployeeSpringMVC/delRule/5&quot;" data-method="delete" class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
Delete
</button>
</td>
</tr>

</tbody>
</table>

正如您所看到的,有一个编辑按钮,我可以编写一个函数来识别对该按钮的点击,如下所示

$('.editBtn').click(function(){
alert("test");
});

我还需要特定行中的数据来进行函数中的某些处理。我如何从表行中获取这些数据。如果有更好的方法,欢迎提出。

我看到了问题here但我不明白答案的这种说法。

var id = $(this).attr('id');

id是如何传递给函数的。这里指定的id是什么。

<input id="btn" type="button" value="click" />

最佳答案

因为您可能需要所有 <td>在一行中,除了当前的一行之外,我建议使用 siblings()最接近的方法<td> :

$('.editBtn').click(e => {
e.preventDefault();
const $td = $(e.target).closest('td');
const fields = Array.from($td.siblings('td').map((i, e) => $(e).text()));
console.log(fields);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Start Date</th>
<th>Severity</th>
<th>Edit Data</th>
</tr>
</thead>
<tbody id="myTable">

<tr style="display: table-row;">
<td>New Rule</td>
<td>New Rule</td>
<td>2017-04-04</td>
<td>High</td>
<td>
<button class="btn btn-primary btn-sm editBtn">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
Edit
</button>
<button onclick="window.location =&quot;/EmployeeSpringMVC/delRule/5&quot;" data-method="delete" class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
Delete
</button>
</td>
</tr>

</tbody>
</table>

关于javascript - 单击按钮将值传递给 jquery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43232589/

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