gpt4 book ai didi

javascript - jQuery .on() 事件不适用于 :lt() selector

转载 作者:行者123 更新时间:2023-11-28 12:34:44 25 4
gpt4 key购买 nike

我正在尝试在每个表数据上生成点击事件<TD>除了最后一个<td>但它只适用于第一行而不适用于其余行。

HTML:

<table class="table" style="width:100%;">
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>

JS代码:

$('.table tbody').on('click', 'tr td:lt(3)', function(){
// Trying to check the click event
console.log('working');
});

JSFIDDLE

jsfiddle

如果我删除 :lt(3)选择器然后它工作正常,但我不知道为什么它不能与 less then 选择器一起使用?

最佳答案

嗯,这就是 :lt() selector 的方式作品:

The index-related selectors (including this "less than" selector) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set. For example, if elements are first selected with a class selector (.myclass) and four elements are returned, these elements are given indices 0 through 3 for the purposes of these selectors.

在您的情况下,首先匹配 tr td ,它匹配 16 个单元格,然后过滤结果集中的前 3 个元素。您可以像这样修改代码:

// trap clicks on .table tbody and filter all td elements
$('.table tbody').on('click', 'td', function () {
if ($(this).index() < 3) {
console.log('working');
}
});

或者更好,使用 CSS3 :nth-child()选择器是 also available in jQuery :

// trap clicks on .table tbody and filter all td elements
// that are "-n+3"th child of their parent
$('.table tbody').on('click', 'td:nth-child(-n+3)', function () {
console.log('working');
});

第 n 个子选择器是 explained here .

关于javascript - jQuery .on() 事件不适用于 :lt() selector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18374908/

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