使用 jQuery 动态添加 Select 选项:根据 Name 属性动态增加 Option
假设我们有一个下拉框的 HTML 代码如下:
<select name='fruit'></select>
我们可以使用 jQuery 来动态增加 option,代码如下:
// 定义一个数组,包含水果选项
var fruits = ['Apple', 'Banana', 'Orange'];
// 遍历水果选项,为 select 元素动态增加 option
$.each(fruits, function(index, fruit) {
$('select[name="fruit"]').append('<option value='' + fruit + ''>' + fruit + '</option>');
});
这段代码会将数组中的每个水果选项,都动态增加到 name 为 'fruit' 的 select 元素中。每个 option 的 value 和显示文本都设置为水果选项的名称。
原文地址: https://www.cveoy.top/t/topic/ol0A 著作权归作者所有。请勿转载和采集!