在我的專案中,我試圖創建一個動態的產品表,但到現在我還不能從我的JSON中填寫欄位。
下面是我的JS
//Creating Select
const createOptionField = document.createElement("select")
createOptionField.id = 'select-options'。
createOptionField.classList.add("product-options","product-sheet-infos")
createContainer.appendChild(createOptionField)
//Generating Option[/span]。
const createOption = document.createElement('option')
createOption.value = "default"
createOptionField.appendChild(createOption)
//Fill options with JSON array(createOption)
const select = document.getElementById("select-options"/span>)
const options=article.lenses。
for(var i=0; i< options.lenght; i )
{
var option = document.createElement("Option") 。
inner = document.createTextNode(options[i])
option.appendChild(inner)。
select.insertBefore(option,select.lastChild)
}
這里是我的Json中的陣列
Array(3) [ "50mm 1。 8"/span>, "60mm 2.8"/span>, "24-60mm 2.8/4.5"/span> ]
我的控制臺沒有任何錯誤,我不知道問題來自哪里
uj5u.com熱心網友回復:你可以看看這個,它應該對你的情況有幫助 作業演示
var selectEl = document. querySelector(".select") 。
data = ["one","wo","three"]
loadFromJson(selectEl,data)
function loadFromJson(el,json){
//從json中追加選項。
json.forEach(each=>/span>{
var newEl = document.createElement("option"/span>)
newEl.innerText = each
newEl.value = each
el.appendChild(newEl)
})
}
uj5u.com熱心網友回復:
嗨,米歇爾。 我已經對你的代碼做了一些修改。 它作業得很好。
你只需要在回圈和options.length
const createOptionField = document. createElement("select"/span>)
createOptionField.id = 'select-options'。
createOptionField.classList.add("product-options","product-sheet-infos")
//使用你的容器createContainer。
document.getElementById("demo").appendChild(createOptionField)
//Generating Option。
const createOption = document.createElement('option')。
createOption.value = "default"。
createOption.text='default'。
createOptionField.appendChild(createOption)。
//Fill options with JSON array
const select = document.getElementById("select-options"/span>)
//將此作為你的陣列。
const options = [ "50mm 1.8", "60mm 2.8", "24-60mm 2.8/4.5" ] 。
for(var i=0; i< options.length; i ){
//Create single option with text and valuevar option = document.createElement("option") 。
option.value = options[i];
option.text= options[i];
select.insertBefore(option,select.lastChild)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/307038.html
標籤:
