`div input[type='checkbox']:lt(2)` 只选择第一行

`div input[type='checkbox']:lt(2)` only selecting first row

我想在用户点击每行前两个 <input> 中的任何一个时发出警报,但我当前的代码仅适用于第一行。我怎样才能修复我的选择器以适用于其余的行?

HTML:

<div>
    <input type='checkbox' />
    <input type='checkbox' />
    <input type='checkbox' />
</div>
<div>
    <input type='checkbox' />
    <input type='checkbox' />
    <input type='checkbox' />
</div>
<div>
    <input type='checkbox' />
    <input type='checkbox' />
    <input type='checkbox' />
</div>

jQuery:

 $("body").on("click", "div input[type='checkbox']:lt(2)", function() {
    alert("x");
});

我这里有一个 JSFiddle:http://jsfiddle.net/yxmeA/393/

您需要使用 :nth-child(-n+2):

这样的选择器
$("body").on("click", "div input[type='checkbox']:nth-child(-n+2)", function() {
    alert("x");
});

这是因为您的 :lt(2) 选择器选择了所有输入,然后仅过滤到前 2 个。在这里,我们检查它是否是其父级的前 2 个子级。

$("body").on("click", "div input[type='checkbox']:nth-child(-n+2)", function() {
    alert("x");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
    <input type='checkbox' />
    <input type='checkbox' />
    <input type='checkbox' />
</div>
<div>
    <input type='checkbox' />
    <input type='checkbox' />
    <input type='checkbox' />
</div>
<div>
    <input type='checkbox' />
    <input type='checkbox' />
    <input type='checkbox' />
</div>

您可以查看 nthmaster.com 了解有关此强大选择器的更多信息。

也许给元素本身编号是个好主意,因为您的程序逻辑似乎取决于元素位置。 CSS 选择器非常强大,但可能有更简单的解决方案。例如:

HTML:

<div data-y="0">
    <input type='checkbox' data-x="0"/>
    <input type='checkbox' data-x="1" />
    <input type='checkbox' data-x="2" />
</div>
<div data-y="1">
    <input type='checkbox' data-x="0" />
    <input type='checkbox' data-x="1" />
    <input type='checkbox' data-x="2" />
</div>
<div data-y="1">
    <input type='checkbox' data-x="0" />
    <input type='checkbox' data-x="1" />
    <input type='checkbox' data-x="2" />
</div>

JS

$("div > input[type='checkbox']").on("click", function() {
    alert($(this).data('x') + ', ' + $(this).parent().data('y'));
});

http://jsfiddle.net/hhqcwepf/

您可以使用极其简单的选择器来做到这一点。 Select 所有 <input> 个未被其他两个前置的元素。

$('div input:not(input+input+input)').click(function() {
  alert("x");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
    <input type='checkbox' />
    <input type='checkbox' />
    <input type='checkbox' />
</div>
<div>
    <input type='checkbox' />
    <input type='checkbox' />
    <input type='checkbox' />
</div>
<div>
    <input type='checkbox' />
    <input type='checkbox' />
    <input type='checkbox' />
</div>