动态创建的值<select>未设置

问题描述 投票:0回答:1

// 首先我创建选择元素

 let list;
    let sel = document.createElement('select');
    sel.style.fontSize = "18px";
    sel.style.float = "right";
    sel.style.marginTop = "12px";
    sel.style.marginRight = "10px";
    sel.id = "select" + x;

// 接下来我为选择元素创建选项

    for (let y = 0; y < selectSizes.length; y++){
        list = document.createElement('option');
        list.value = Number(selectCosts[y]);
        let selectedValue = Number(list.value).toFixed(2);
        list.appendChild(document.createTextNode("Size - " + selectSizes[y] + " : $" + selectedValue));
        sel.innerHTML += list.outerHTML;
    }

//最后我尝试获取选择元素的值,但它抛出一个空错误

    alert(document.getElementById("select"+x).value);
    div1.appendChild(sel);

未设置选择元素的值。有谁知道为什么吗?

javascript dom
1个回答
0
投票

我没有你的数组,但创建了一些带有一些值的数组,然后使用它们创建一个新的选择。您可以使用它作为传递给函数的模式,在其中放置选择和要使用的名称/值对。

function createSelect(container, optionValues) {
  const selectCount = document.querySelectorAll('select').length;
  let selectList = document.createElement("select");
  selectList.id = "select-" + selectCount;
  optionValues.forEach((ov, key) => {
    selectList[key] = new Option(ov.name, ov.value);
  });
  selectList.classList.add('selector-cool');
  container.appendChild(selectList);
}

let selectSizes = [{
  name: "small",
  value: 0
}, {
  name: "medium",
  value: 0
}, {
  name: "giant",
  value: 0
}];
const selectCosts = [1.23, 9.88, 7.54];
//set costs
for (let y = 0; y < selectSizes.length; y++) {
  selectSizes[y].value = selectCosts[y];
}
// setup the names
for (let y = 0; y < selectSizes.length; y++) {
  selectSizes[y].name = `Size - ${selectSizes[y].name} : $${selectCosts[y]}`;
}
//Create and add options, append to container
const container = document.querySelector('.select-container');
createSelect(container, selectSizes);
// do stuff with it including add a change event handler
const mySelect = container.querySelector('select.selector-cool');
mySelect.value = selectSizes[1].value;

console.log(mySelect.value);
mySelect.addEventListener('change', function(event) {
  console.log('NewValue:', this.value);
  console.log('ID:', this.id);
});
body {
  font-size: 16px;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.select-container {
  padding-top: 0.667em;
  padding-right: 0.555em;
}

.selector-cool {
  font-size: 1.125em;
  color: #0000FF;
  border: solid 1px #00C0FF;
  padding: 0.5em;
  border-radius: 0.5em;
  background-color: #00ff0020;
}

.selector-cool option {
  padding: 0.5em;
  font-size: 1.125em;
}

.selector-cool option:checked {
  background-color: #0000ff20;
  font-weight: 600;
  color: #ff0000;
}
<div class="select-container"></div>

© www.soinside.com 2019 - 2024. All rights reserved.