jquery 选择器排除包含具有焦点的输入的元素

jquery selector exclude elements containing input with focus

我今天花了很多时间试图想出这个,但无济于事。

我正在尝试 table 中的 select 行具有可见的输入元素,但不包括包含具有焦点的输入的行。

我的最佳猜测:

$('tr:has(input:visible)').not('tr:has(input:focus)')
$('tr:has(input:visible):not(:has(input:focus))')

这些都没有删除具有焦点输入的行。我读到 :focus 是伪造的 select 或者,这是我的问题的一部分,还是所有带冒号的标签?

是否可以在 selector 内执行此操作?我也可以使用条件手动循环,但我希望能够避免这种情况。

您可以将 .filter() 到 return tr 元素与未聚焦的 input 元素一起使用。

本例中,.is(':focus')用于判断childinput是否被聚焦。如果它 不是 ,那么它会被 return 编辑并添加到 tr 元素的集合中。

Example Here

var tr = $('tr:has(input:visible)').filter(function () {
    return !$('input', this).is(':focus');
});

不过,基于 this example,看起来您原来的两个 jQuery 选择器都工作正常。也许您在查询 DOM 时 input 元素没有焦点?

已更新,实际上我在你的问题中测试了你的两个 jQuery 选择器,根据我的测试,它们工作正常:-) 根据查询找到的元素数量的长度打印到控制台。

$("#firstInput").focus(); // set focus


console.log($('tr:has(input:visible)').not('tr:has(input:focus)').length) // 2

console.log($('tr:has(input:visible):not(:has(input:focus))').length); // 2

//$('tr:has(input:visible):not(:has(input:focus))').remove(); // removes two rows

//$('tr:has(input:visible)').not('tr:has(input:focus)').remove() // removes two rows
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Inputs</th>
    </tr>
    <tr>
        <td>Peter</td>
         <td>
            <input id="firstInput" type="text"/>
        </td>
        <td>
            <input id="firstIIInput" type="text"/>
        </td>
    </tr>
    <tr>
        <td>Lois</td>
        <td>
            <input id="2ndInput" type="text"/>
        </td>
        <td>
            <input id="2ndIIInput" type="text"/>
        </td>
    </tr>
    <tr>
        <td>Gabriel</td>
        <td>
            <input id="3rdInput" type="text"/>
        </td>
        <td>
            <input id="3rdIIInput" type="text"/>
        </td>
    </tr>
</table>