如何使用下拉列表更新json值



有人能教我如何使用下拉列表更新json值吗。在JavaScript 中

HTML:

<select id="currency" onchange="getSelectValue();">
<option value="Singapore Dollar">Singapore Dollar</option>
<option value="USD">USD</option>
<option value="Malaysia Riggit">Malaysia Riggit</option>
</select>

JSON:

{
"products": [
{
"name": "Apple",
"price": "2.50",
"code": "SGD"
},
{
"name": "Orange",
"price": "2.50",
"code": "SGD"
}
]
}

您可以像这样在javascript中创建一个select,重点关注<script />

<!DOCTYPE html>
<html lang="en">
<head>
<title>Javascript - Select</title>
</head>
<body>
<div id="main"></div>
</body>
<script>
const {products} = JSON.parse('{ "products": [ { "name": "Apple", "price": "2.50", "code": "SGD" }, { "name": "Orange", "price": "2.50", "code": "SGD" } ] }');
const select = document.createElement("select");
select.id = 'currency';
select.onchange = ({target: {value}}) => console.log(value);
products.forEach(({code, name}) => {
const option = document.createElement("option");
option.label = name;
option.value = code;
select.appendChild(option);
});
const main = document.getElementById('main');
main.appendChild(select);
</script>
</html>

编辑:

将";值";作为函数的参数

<select id="currency" onchange="getSelectValue(value)">
<option value="SGD">Singapore Dollar</option>
<option value="USD">USD</option>
<option value="MR">Malaysia Riggit</option>
</select>

函数定义应该是这样的:

const getSelectValue = (selectedValue) => {
console.log(selectedValue);
// Your code...
};

这是代码示例。

var json=JSON.parse( "Your json which you mentioned above");
var products= json.products;

string selectlist="";
if(products.length>0)
{

selectlist += "<select>";
for(var i = 0; i < products.length; i++) {

var currency = json[i];
selectlist += "<option value="+currency.code+"> "+currency.code+"  </option>";
}   
selectlist += "</select>"
if("body").append(selectlist);
}

最新更新