相信我,我一直在网上寻找几个小时的例子。他们似乎都没有帮助。
我正在制作一张桌子。有一些列有下拉菜单,我已为每个菜单分配了ID。在循环内部,我正在尝试为每个下拉菜单分配选定的值。
var row$ = $('<tr/>');
function updateDataBodyGenerator(myList) {
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
var colIndex = 0;
for (var key in myList[i]) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
var severityDropDownMenu = "severityDropDownMenu" + i;
colIndex++;
switch (key) {
case "Test Case":
...
break;
case "Test Result":
...
break;
case "Severity":
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>'+
'<option value="Yellow">Yellow</option>';
row$.append($(severitySting));
//failed
//$("#severityDropDownMenu" + i).val(cellValue);
//failed
//var selectorString = "#" + severityDropDownMenu.toString();
//$(selectorString).val("Green");
//failed
//$("#" + severityDropDownMenu).val(cellValue);
//failed
//var selectorString = '#' + severityDropDownMenu;
//$(selectorString).val(cellValue);
//works
//$('#severityDropDownMenu0').val(cellValue);
...
正如你在评论中看到的那样,我尝试了几种方法,只有一种方法是$('#severityDropDownMenu0')。val(cellValue);但这只会改变1个下拉菜单。
感谢您的时间和帮助。
答案 0 :(得分:0)
目前,您正在尝试使用#
选择器按ID定位下拉列表。
此处的问题(如评论中所述)是此选择器将在DOM中搜索元素,但是因为您从未将此元素添加到DOM,所以它不存在于页面上;选择器不会返回任何内容。
您可以做的是将severitySting
转换为jQuery元素以设置其值。只要您做追加它,就会正确设置该值。像这样:
var $severity = $(severitySting); //This is the <td>
var $dropdown = $severity.find("select") //This is the <select>
$dropdown.val(cellValue); //Set dropdown value
<强>演示:强>
var severityDropDownMenu = "mytest";
var cellValue = "Yellow";
var severitySting = '<td><select id="' + severityDropDownMenu + '" class="dropDownMenu">' +
'<option value="Red">Red</option>' +
'<option value="Green">Green</option>' +
'<option value="Yellow">Yellow</option>';
var $severity = $(severitySting);
var $dropdown = $severity.find("select");
$dropdown.val(cellValue);
$("tr").append($severity);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr></tr>
</table>
&#13;