”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 在选择元素中动态创建选项

在选择元素中动态创建选项

发布于2024-11-20
浏览:927

Dynamically create option in select element

有两种动态创建选项的方法:

1) 使用 Option 构造函数和 add() 方法

2) 使用 DOM 方法

1) 使用 Option 构造函数和 add() 方法:

let newOption = new Option('Option Text','Option Value');
const select = document.querySelector('select'); 
select.add(newOption,undefined);

2) 使用 DOM 方法:

// create option using DOM
const newOption = document.createElement('option');
const optionText = document.createTextNode('Option Text');
// set option text
newOption.appendChild(optionText);
// and option value
newOption.setAttribute('value','Option Value');

const select = document.querySelector('select'); 
select.appendChild(newOption);
版本声明 本文转载于:https://dev.to/jharna_khatun/dynamically-create-option-in-select-element-d6c?1如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3