如果<a> is last child execute code</a>

时间:2012-08-05 22:37:37

标签: jquery if-statement

我有一些链接到2个不同页面的代码。当您在一个页面上时,另一个是链接。例如

<div id="options">
<a href="#">other</a>
<p>current</p>
</div>

<div id="options">
<p>current</p>
<a href="#">other</a>
</div>

如果a是最后一个孩子但不确定正确的语法,我想执行if语句? 例如

if {/* #options a is last child*/}
{
     alert("hello");
}

2 个答案:

答案 0 :(得分:2)

您可以使用.is()函数检查元素是否与伪选择器匹配:

if ($('#options a').is(':last-child')) {
  alert('hello');
}

它最终具有可读性。

演示:http://jsfiddle.net/acWUT/

答案 1 :(得分:2)

首先,你有两个具有相同options id的div - 根本不起作用。

但总的来说,为了获得页面上的最后一个,你可以这样做:

var lastA = $("a:last")[0];

然后在点击处理程序中进行比较:

if (lastA === this) 
{
     alert("hello");
}
相关问题