首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在父<optgroup>中动态创建<option>元素

在父<optgroup>中动态创建<option>元素可以通过JavaScript来实现。以下是一个实现的示例代码:

代码语言:txt
复制
<!DOCTYPE html>
<html>
<head>
<script>
function createOptions() {
  // 获取父<optgroup>元素
  var parentOptgroup = document.getElementById("parentOptgroup");

  // 创建新的<option>元素
  var newOption1 = document.createElement("option");
  newOption1.text = "选项1";
  var newOption2 = document.createElement("option");
  newOption2.text = "选项2";
  var newOption3 = document.createElement("option");
  newOption3.text = "选项3";

  // 将新的<option>元素添加到父<optgroup>元素中
  parentOptgroup.appendChild(newOption1);
  parentOptgroup.appendChild(newOption2);
  parentOptgroup.appendChild(newOption3);
}
</script>
</head>
<body>
<select>
  <optgroup id="parentOptgroup" label="父组">
    <option>默认选项</option>
  </optgroup>
</select>

<button onclick="createOptions()">创建选项</button>

</body>
</html>

上述代码中,首先获取父<optgroup>元素的引用,然后使用document.createElement()函数创建新的<option>元素,并为其设置text属性。最后,使用appendChild()函数将新的<option>元素添加到父<optgroup>元素中。

点击"创建选项"按钮后,新的<option>元素会动态地添加到父<optgroup>元素中。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

  • 领券