我已经弄清楚如何动态地将选项附加到选择框 - 但添加内容会附加到结尾,而不会包含在选项组中。
我怎样才能做到这一点?以下是当前仅附加到选择菜单的代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
roles = $("#roles").selectmenu();
roles.append("<option value='"+'test!'+"'>" + 'test!' + "</option>");
roles.selectmenu();
// let's say I wanted to append to the optgroup labeled 'Your roles' instead. How?
});
</script>
</head>
<body>
<div id="role-select" style="margin-left:30px; margin-top:-10px; float:left;">
<form action="#">
<fieldset>
<label for="roles">Select a role to edit</label>
<select name="roles" id="roles">
<optgroup label="Your roles">
<option value="empty">random 1</option>
<option value="noreason">2</option>
</optgroup>
<optgroup label="Default roles">
<option value="vvv">3</option>
<option value="somsdfsdfile">4</option>
</optgroup>
</select>
</fieldset>
</form>
</div>
</body>
</html>
答案 0 :(得分:1)
您需要选择要附加到的opgroup。例如:
var roles = $("#roles");
roles.find('optgroup[label="Your roles"]').append("<option value='"+'test!'+"'>" + 'test!' + "</option>");