【问题标题】:Last element of Class类的最后一个元素
【发布时间】:2013-02-06 21:12:09
【问题描述】:

如何检查某个类的元素是否是该类的最后一个?

<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div> // I want to check if this is the last element of this class
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>

【问题讨论】:

  • 你如何确定我们正在谈论的实例?

标签: javascript jquery class css-selectors


【解决方案1】:

下面会循环每个 div 并说出哪个 div 是最后一个 div

var count = $('div.foo').length;

$('div.foo').each(function(index){
  if(index == (count-1))
  {
    alert("this is last div" + index);
  }
});

这样你可以得到类的最后一个元素

 var last_foo_div = $('div.foo:last');

   var foodivs= $('div.foo');
   var lastdiv  = foodivs.last();

【讨论】:

  • 获取最后一个元素,它不检查我们已经拥有的元素是否是最后一个元素。
【解决方案2】:
if ($('.foo').next('.foo').length == 0)
   alert("This is last Element")

【讨论】:

  • 这只会返回第一个“bar”元素。
【解决方案3】:

由于我不确定您是如何识别此变量的,假设 $foo 是该特定元素的 jQuery 对象。

你可以这样做:

if (!$foo.next(".foo").length){
   //its the last foo
}

现场演示: http://jsfiddle.net/2W6eT/

【讨论】:

    猜你喜欢
    • 2017-11-28
    • 2012-04-02
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2015-10-19
    • 2016-04-20
    • 2013-01-12
    • 1970-01-01
    相关资源
    最近更新 更多