jQuery UI selectmenu -如何添加选项到optgroup



我已经弄清楚如何动态地将选项附加到选择框中-但是添加的内容被附加到末尾,而不包含在optgroup中。

我怎么才能做到呢?下面是当前只是附加到selectmenu的代码:

<!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>

您需要选择要附加到的操作组。例如:

var roles = $("#roles");
roles.find('optgroup[label="Your roles"]').append("<option value='"+'test!'+"'>" + 'test!' + "</option>");

最新更新