使用 jQuery 选择仅包含“指定文本”而不包含其他文本的 tds

Select the tds containing a only the "specified text" and nothing else using jQuery

本文关键字:文本 包含 tds 其他 指定文本 选择 jQuery 使用      更新时间:2023-09-26

有什么方法可以选择仅包含指定文本而不包含其他文本的td吗? 我尝试了以下方法:

$("tr td:contains('1')")

但它也返回td文本中某处有 1 的td。需要明确的是,我试图从下面给出的 html 中获取<td>1</td>,但它不断返回所有这些td

<tr>
     <td>1</td>
     <td>This contains 1 as well</td>
     <td><td>And this one contains 1 as well</td>
</tr>

有什么方法可以强制它只返回那些只包含文本中1而不包含其他内容的td

使用 .filter()

$('td').filter(function (i, el) {
    return this.innerHTML == '1';
}).css('background-color','blue');

有很多选项,过滤器等。

一种简单的方法是:

$('td').each(function (i, el) {
    if (el.innerHTML === '1') {
        // DO SOMETHING
        console.log('It has only a 1 in it');
    }
});

使用 .map()

var selectors = $('tr td').map(function () {
    if (this.innerHTML == '1') {
        return $(this);
    }
});
//result: selectors is the td elements with text "1".