如何在jquery中选择具有相同类和相同类型的最后一个元素的前一个html元素

时间:2015-07-22 21:27:49

标签: jquery html

如果我有这段代码

<div id="someId">
  <select class="example">
    <option value="1">some example</option>
  </select>
  <div class="example"></div>
  <select class="example">
    <option value="1">another example</option>
  </select>
</div>

如果我不知道选择元素的数量,我需要获取最后一个选择元素值的前一个选择元素
我怎么能用jquery做这个 请有人帮我这个吗

1 个答案:

答案 0 :(得分:1)

使用:eq()

var selectLength = $('select').length;
var secondToLast = $('select:eq('+(selectLength-2)+')');

var secondToLast = $('select:eq(-2)');

&#13;
&#13;
var selectLength = $('select').length;
var secondToLast = $('select:eq(' + (selectLength - 2) + ')');

console.log(secondToLast);
secondToLast = $('select:eq(' + (selectLength - 2) + ')');


console.log(secondToLast);

secondToLast.css('background', 'green');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="someId">
  <select class="example">
    <option value="1">some example</option>
  </select>
  <select class="example">
    <option value="1">some example</option>
  </select>
  <select class="example">
    <option value="1">some example</option>
  </select>
  <select class="example">
    <option value="1">some example</option>
  </select>
  <select class="example">
    <option value="1">some example</option>
  </select>
  <select class="example">
    <option value="1">another example</option>
  </select>
</div>
&#13;
&#13;
&#13;