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

标签 javascript jquery

我正在尝试在每个表数据上生成点击事件<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/

相关文章:

jquery - slider 和菜单 z-index 问题定位

javascript - 是否可以在主显示器以外的其他显示器上显示网络推送通知?

javascript - next() 到中间 Observable

jquery - 类 html 用符号替换字符串

jquery - 如何使用 jquery 在鼠标悬停时显示/隐藏 div?

javascript - 涟漪效果CSS | ipad native 应用程序

javascript - 可见绑定(bind)在 Knockout js 中不起作用

javascript - React Native Firebase DataSnapshot

php - 浏览器重定向

javascript - 调整容器的大小,两个灰色方 block 应该尽可能地增长,受对 Angular 线的约束..简单的方法吗?