[英]JavaScript - Append option element to a select element not working
我正在嘗試使用JavaScript將option元素附加到select元素,但無法正常工作。 我將代碼分解成碎片,並在所有我想到的錯誤地方都調用了console.log()
,但是除了appendChild方法之外,其他一切似乎都可以正常工作。
我也嘗試過: select.add(new option('value1', 'value2')
但是沒有用。
JavaScript代碼:
var divTo = document.getElementById('selectProduct');
console.log(divTo);
if (whereTo == 'selectProduct'){
console.log('inside if loop');
for (i = 0 ; i < 2 ; i++){
console.log('inside for loop')
console.log('products[i] = ' +products[i]);
var addedOption = new Option();
addedOption.label = products[i];
console.log("addedOption label = "+addedOption.label);
divTo.appendChild(addedOption);
console.log("divTo constructor = "+divTo.constructor.name);
console.log("addedOptionConstructor = "+addedOption.constructor.name);
// also tried: divTo.options.add(new Option("valor1", "valor2")); instead of appendChild
// also tried: addedOption.text instead of addedOption.label
}
}
控制台日志:
inside if loop
inside for loop
products[i] = Armada Argentina
addedOption label = Armada Argentina
divTo constructor = HTMLSelectElement
addedOptionConstructor = HTMLOptionElement
<select class="selectfield" id="selectProduct" name="product"></select>
有人可以幫我嗎?
PS:我真的是編程新手。 如果錯誤很明顯,我感到抱歉。
您想將option
元素動態添加到select
框,對嗎?
看到這個: jsfiddle
用這個,
var divTo = document.getElementById('selectProduct');
if (whereTo == 'selectProduct') {
console.log('inside if loop');
for (i = 0 ; i < 2 ; i++) {
var addedOption = document.createElement("option");
addedOption.text = products[i];
divTo.add(addedOption);
}
}
createSelect()
通過傳遞2個等長數組和要附加到的目標元素來創建選擇和選項。
簽名
createSelect(textArray, valueArray, target)
參量
- textArray :字符串數組(每個字符串設置為選項的內容)的長度必須等於valueArray的長度 。
- valueArray :字符串數組(每個字符串設置為選項的值)的長度必須等於textArray的長度 。
- target :一個字符串,語法與CSS和jQuery選擇器相同。
var txt = ['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE']; var val = ['1', '2', '3', '4', '5']; function createSelect(textArray, valueArray, target) { var tgt = document.querySelector(target); var sel = document.createElement('select'); var qty = textArray.length; for (let i = 0; i < qty; i++) { var opt = document.createElement('option'); opt.textContent = textArray[i]; opt.value = valueArray[i]; sel.appendChild(opt); } tgt.appendChild(sel); } createSelect(txt, val, "body");
對於onload
,將其包裝在另一個函數中:
function init() { var txt = ['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE']; var val = [1, 2, 3, 4, 5]; function createSelect(textArray, valueArray, target) { var tgt = document.querySelector(target); var sel = document.createElement('select'); var qty = textArray.length; for (let i = 0; i < qty; i++) { var opt = document.createElement('option'); opt.textContent = textArray[i]; opt.value = valueArray[i]; sel.appendChild(opt); } tgt.appendChild(sel); } createSelect(txt, val, "body"); } window.onload = init;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.