如果我有这段代码
<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做这个
请有人帮我这个吗
答案 0 :(得分:1)
使用:eq()
var selectLength = $('select').length;
var secondToLast = $('select:eq('+(selectLength-2)+')');
或
var secondToLast = $('select:eq(-2)');
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;