How to select just previous row of the last row?
如何选择最后一行的前一行?
My html code:
我的HTML代码:
<table id="table1">
<tr><td>test</td></tr>
<tr><td>test</td></tr>
<tr><td>test</td></tr>
<tr><td><select></select></td></tr>
<tr><td>test</td></tr>
</table>
Now I want to give option to the using jquery.
现在我想给使用jquery选项。
js:
$('#table1 tr:last select').prev().append("<option>rose</option>");
But it doesn't worked. Please help.
但它不起作用。请帮忙。
fiddle: http://jsfiddle.net/xzj5m3w8/
3 个解决方案
#1
tr:last select
will look for select in last row. you need to find the last row first, traverse to previous tr and then find select element in it. Like this:
tr:last select将在最后一行中查找select。你需要先找到最后一行,遍历前一个tr,然后在其中找到select元素。像这样:
$('#table1 tr:last').prev().find('select').append("<option>rose</option>");
From the markup it appears that you have only single select. if that is the case always, you need not have to do all the traversing and stuff. $('#table1 select')
will work for targeting single select element.
从标记看,您只有一个选择。如果总是如此,你不需要做所有的遍历和东西。 $('#table1 select')将用于定位单个选择元素。
#2
In the specific table there is only one select
element, so you can just use find()
in the parent table:
在特定的表中只有一个select元素,所以你可以在父表中使用find():
$('#table1').find('select').append('<option>rose</option>');
Another approach would be this:
另一种方法是:
$('#table1 tr').each(function() {
var that = $(this);
var l = that.find('select').length;
if (l > 0) {
// the row has a select element ...
}
});
#3
Try this :
试试这个 :
$('#table1 tr:nth-last-child(2)').find('select').append("<option>rose</option>");
#1
tr:last select
will look for select in last row. you need to find the last row first, traverse to previous tr and then find select element in it. Like this:
tr:last select将在最后一行中查找select。你需要先找到最后一行,遍历前一个tr,然后在其中找到select元素。像这样:
$('#table1 tr:last').prev().find('select').append("<option>rose</option>");
From the markup it appears that you have only single select. if that is the case always, you need not have to do all the traversing and stuff. $('#table1 select')
will work for targeting single select element.
从标记看,您只有一个选择。如果总是如此,你不需要做所有的遍历和东西。 $('#table1 select')将用于定位单个选择元素。
#2
In the specific table there is only one select
element, so you can just use find()
in the parent table:
在特定的表中只有一个select元素,所以你可以在父表中使用find():
$('#table1').find('select').append('<option>rose</option>');
Another approach would be this:
另一种方法是:
$('#table1 tr').each(function() {
var that = $(this);
var l = that.find('select').length;
if (l > 0) {
// the row has a select element ...
}
});
#3
Try this :
试试这个 :
$('#table1 tr:nth-last-child(2)').find('select').append("<option>rose</option>");