我有一个表,我在其中添加一些行
....
<td><strong class="has-text-success thisState">Connect</strong></td>
<td><a class="is-danger buttonDisconnect"><strong>Disconnect</strong></a></td>
....
我需要通过点击 .buttonDisconnect ... 来选择 .thisState 我尝试了这个但没有成功
$('#table').on('click', ".buttonDisconnect", function () {
.... disconnection code
$(this).html("<strong>Connect</strong>");
$(this).toggleClass("buttonDisconnect is-danger buttonConnect has-text-success");
// toggle state
$(this).prev(".thisState").text("Disconnect");
$(this).prev(".thisState").toggleClass("has-text-danger has-text-success");
});
最佳答案
如果将选择器传递给.prev
,仅当前一个元素与选择器匹配时,才会选择前一个元素。但您传递的选择器是针对前一个元素的子 - 它与前一个元素不匹配。
另一个问题是单击的元素是 <a>
,而不是 <td
> - 导航到父级 <td>
在转到上一个之前。
无条件导航到上一个元素并使用.children
通过选择器转到其子级过滤,然后执行您需要执行的操作:
const $prevStrongState = $(this).parent().prev().children('.thisState');
$prevStrongState.text("Disconnect");
$prevStrongState.toggleClass("has-text-danger has-text-success");
$('#table').on('click', ".buttonDisconnect", function() {
$(this).html("<strong>Connect</strong>");
$(this).toggleClass("buttonDisconnect is-danger buttonConnect has-text-success");
const $prevStrongState = $(this).parent().prev().children('.thisState');
$prevStrongState.text("Disconnect");
$prevStrongState.toggleClass("has-text-danger has-text-success");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<td><strong class="has-text-success thisState">Connect</strong></td>
<td><a class="is-danger buttonDisconnect"><strong>Disconnect</strong></a></td>
</tr>
</table>
关于javascript - jquery 在另一个表之前选择表中的一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60576835/