我有下表
<table id="table_device">
<tr>
<td> First td </td>
<td> Second td </td>
<td>
<select class="base_MD">
<option>A value</option>
<option>Another value</option>
<option>And another one</option>
...
</select>
</td>
<td> The value </td>
</tr>
<tr></tr>
<tr></tr>
...
</table>
如何设置<select>
其中<option>
每个 'The value'
与第四个子项(名为 <tr>
)匹配标签?
编辑
我尝试了以下方法
$('#table_device').find('tr').each(function()
{
var value = $(this).find(':nth-child(4)').html();
$('select').each(function()
{
if($(this).text() == value)
{
var id = $(this).val();
}
$(this).eq(id).prop('selected', true);
})
});
但是没有成功... 我确信事情没那么复杂,但我的头很快就会爆炸
最佳答案
您可以迭代每个选择元素。从下一个 td 获取文本并用它来按文本设置选项。像这样:
$('#table_device select').each(function(){
var nexttdtext = $(this).parent().next('td').text();
$(this).find("option").filter(function() {
return this.text == nexttdtext;
}).attr('selected', true);
});
Working Demo
关于javascript - JQuery 设置从字符串中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31655640/