内部javascript
<?php
echo 'var packages_disc = '.json_encode($packages).';';
?>
alert(JSON.stringify(packages_disc));
这是警报输出
[
{"id":"3","package_name":"Standard","invoice_amount":"30000"},
{"id":"4","package_name":"Premium","invoice_amount":"50000"},
{"id":"5","package_name":"Luxury","invoice_amount":"120000"}
]
我想获得单个元素并分配给变量
答案 0 :(得分:0)
迭代数组并找到符合条件的对象......
function getPackageByName(name) {
return packages_disc.find(p => p.package_name == name);
}
var packages_disc = [
{"id":"3","package_name":"Standard","invoice_amount":"30000"},
{"id":"4","package_name":"Premium","invoice_amount":"50000"},
{"id":"5","package_name":"Luxury","invoice_amount":"120000"}
];
var premiumPackage = getPackageByName("Premium");
alert(premiumPackage.invoice_amount);
答案 1 :(得分:0)
如果您想要基于invoice_amount
的{{1}},请执行以下操作:
package_name
&#13;
答案 2 :(得分:0)
尝试以下方式:
function getInvoiceAmount(thatObj){
var arr = [{"id":"3","package_name":"Standard","invoice_amount":"30000"},{"id":"4","package_name":"Premium","invoice_amount":"50000"},{"id":"5","package_name":"Luxury","invoice_amount":"120000"}];
var package = thatObj.options[thatObj.selectedIndex].text
var res = arr.filter(function(item, i){
return item.package_name == package
});
console.log(res[0].invoice_amount + ' for package ' +package)
}
<select id="package" onchange="getInvoiceAmount(this)">
<option>Select Package</option>
<option>Standard</option>
<option>Premium</option>
<option>Luxury</option>
</select>