>我有一个 30 列左右的表,我想为每行中显示的下拉列表获取所选选项。我目前有以下内容,但它返回 null 或未定义。
<table class="table table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>Invite Status</th>
</tr>
</thead>
<tbody id="invitees">
<tr>
<td>John</td>
<td>Doe</td>
<td>john@example.com</td>
<td><select class="form-control"><option value="Invitee" selected="selected">Invitee</option><option value="Alternate">Alternate</option></select></td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>john@example.com</td>
<td><select class="form-control"><option value="Invitee" selected="selected">Invitee</option><option value="Alternate">Alternate</option></select></td>
</tr>
<!-- and so on ... Built Dynamically -->
</tbody>
$('#invitees tr').each(function () {
invite_statuses += $('td:last select').find('option:selected').val() + ",";
})
或
$('#invitees tr').each(function () {
invite_statuses += $('td:last select').find('option:selected').text() + ",";
})
我错过了一些明显的东西还是不能这样做?似乎这应该有效...
您可以直接引用选择框。以下解决方案提供每个选择框中的选定项。检查控制台值。
var rst="";
$('select').each(function () {
rst+=$(this).find('option:selected').text()+" ";
});
console.log(rst);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>Invite Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john@example.com</td>
<td><select class="form-control"><option value="Invitee" selected="selected">Invitee</option><option value="Alternate">Alternate</option></td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>john@example.com</td>
<td><select class="form-control"><option value="Invitee" >Invitee</option><option selected="selected" value="Alternate">Alternate</option></td>
</tr>
<!-- and so on ... Built Dynamically -->
</tbody>
看起来您的table
缺少"受邀者"的 id(#( 选择器。一旦有了它,您就可以遍历表行,获取最后一个td
选择值,将其推送到数组,然后将其连接到逗号分隔列表中。此外,您缺少所选内容的结束</select>
。
var invite_statuses = [];
$(document).ready(function() {
$('#invitees tbody tr').each(function() {
var selection = $(this).find('td:last option:selected').val();
console.log(selection);
invite_statuses.push(selection);
});
console.log(invite_statuses.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="invitees" class="table table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>Invite Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john@example.com</td>
<td>
<select class="form-control">
<option value="Alternate">Alternate</option>
<option value="Invitee" selected="selected">Invitee</option>
</select>
</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>john@example.com</td>
<td>
<select class="form-control">
<option value="Alternate" selected="selected">Alternate</option>
<option value="Invitee" >Invitee</option>
</select>
</td>
</tr>
<!-- and so on ... Built Dynamically -->
</tbody>
</table>