[英]jQuery: test if element is first of MATCHED elements
I have several divs that are alerts. 我有几个警报的div。 The user dismisses them and after the final one (which is the FIRST in the DOM) I need to trigger some jquery magic.
用户解散它们并在最后一个(这是DOM中的第一个)之后我需要触发一些jquery魔法。
Here's some simplified HTML: 这是一些简化的HTML:
<body>
<div class="">Bla bla bla</div>
<div class="alert">A</div>
<div class="alert">B</div>
</body>
Here's what I'm trying to do with jquery... 这是我正在尝试用jquery做的...
$(".alert").click( function() {
if ( $(this).is(".alert:first") ) {
//do stuff
}
});
It doesn't work. 它不起作用。 The conditional never returns true.
条件永远不会返回true。 The only way I can get it to work is using
.index()
but that sucks because if the order of the markup changes it will break the script. 我能让它工作的唯一方法是使用
.index()
但这很糟糕,因为如果标记的顺序发生变化,它将破坏脚本。
What am I doing wrong? 我究竟做错了什么?
EDIT: The solution uses .index()
but in a way that I did not realize was possible. 编辑:该解决方案使用
.index()
但在某种程度上我没有意识到是可能的。 It is relative to the matched selection if used in that way. 如果以这种方式使用, 则相对于匹配的选择。 Thanks!
谢谢!
You can code: 你可以编码:
$(".alert").click(function() {
if ($(".alert").index(this) == 0) {
//
}
});
Try this instead : 试试这个:
if ($(this).hasClass("alert") && $(this).is(":first")) {
//do stuff
}
Alternately : 或者:
$(".alert").click( function() {
if ($(".alert").index(this) == 0) {
//do stuff
}
});
Hope this will help !! 希望这会有所帮助!!
you can try this. 你可以试试这个。
$('.alert').click( function() {
if ( ($(this)[0] === $('.alert').first()[0])) {
alert('first');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.