javascript 附加选项以选择和设置选定的选项

bhmjp9jg  于 2022-12-28  发布在  Java
关注(0)|答案(4)|浏览(194)

我正在用编程的方式创建一个带有几个选项的select-元素。我想选择一个特定的选项。为此我使用了option.selected = true。我也尝试了option.selected = 'selected'
这是我的代码:

let select_menu_for_sequence = document.createElement("select");
select_menu_for_sequence.classList.add("sequence");

for (i = 1; i <= 4; i++) {
    let option = document.createElement("option");
    option.text = i;

    if (i == 2) {
        option.selected = true;
    }

    select_menu_for_sequence.appendChild(option);
}

console.log(select_menu_for_sequence.outerHTML)

输出:

<select class="sequence">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
</select>

预期产出:

<select value="2" class="sequence">
    <option>1</option>
    <option selected>2</option>
    <option>3</option>
    <option>4</option>
</select>

我真的找不出我做错了什么。

vd8tlhqk

vd8tlhqk1#

可以使用setAttribute()方法,它只需要两个参数:要添加的属性及其值。

for (i = 1; i <= 4; i++) {
    let option = document.createElement("option");
    option.text = i;

    if (i == 2) {
        option.setAttribute('selected','');
    }

    select_menu_for_sequence.appendChild(option);
}

option.setAttribute('selected','true');
bvk5enib

bvk5enib2#

更新

要在HTML中看到"selected",请使用attribute方法,而不是将其视为带点标记的属性。

select.options[2].toggleAttribute("selected");

selected上使用点标记使其成为HTML中不显示的属性,但很明显.option[2]已被选中。

select.options.selectedIndex = 2;

我认为您忽略了将select附加到<body>或文档中的任何内容。

const select = document.createElement("select");
select.classList.add("sequence");
document.body.append(select);

for (let i=1; i < 5; i++) {
  let option = document.createElement("option")
  option.textContent = i
  select.append(option);
}

//select.options.selectedIndex = 2;
select.options[2].toggleAttribute("selected");
console.log(select.outerHTML);
erhoui1w

erhoui1w3#

你看看这个

let select_menu_for_sequence = document.createElement("select");
select_menu_for_sequence.classList.add("sequence");

for (i = 1; i <= 4; i++)

    select_menu_for_sequence.options[select_menu_for_sequence.options.length]=new Option(i, i);
    
    if (i == 2)
        select_menu_for_sequence.options[select_menu_for_sequence.options.length]=new Option(i, i,true,true);

console.log(select_menu_for_sequence)
yshpjwxd

yshpjwxd4#

<select>元素的值设置为选定选项的值。

select_menu_for_sequence.value = 2;

相关问题