是否可以将 :first
和 :last
选择器与 jQuery 的 on 选择器一起使用?
我希望每个列表项中的第一个链接触发警报。然而,目前只有第一个链接会触发它。
JavaScript 代码:
<script type="text/javascript">
$(document).ready( function(){
$('ul').on("click", "li a:first", function(event) {
alert("test");
});
}
</script>
和 HTML:
<ul>
<li>
<a href="#">Trigger</a>
<a href="#">Don't Trigger</a>
</li>
<li>
<a href="#">Trigger</a>
<a href="#">Don't Trigger</a>
</li>
</ul>
最佳答案
使用 :first-child
代替
$('ul').on("click", "li a:first-child", function(event) {
alert("test");
});
演示: http://jsfiddle.net/joycse06/tuJnv/1/
正如医生所说
The :first pseudo-class is equivalent to :eq(0). It could also be written as :lt(1).
While this matches only a single element, :first-child can match more than one: One for each parent.
:first
将仅匹配一个元素,即选定的一组元素上的第一个元素。其中 :first-child
将为每个父级找到一个(第一个子级
),这正是您想要的。
文档 :first
和 :first-child
关于jQuery - '.on' 和 ':first',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11150891/