我正在使用jQuery自动完成插件,如下所示。这可以正常工作,但我想遍历所选项目的值。例如,如果选择了“产品1”,我想将其记录到控制台:
label : Product 1
value : value1
tax : 18%
我只是不知道该怎么做。如果执行console.log(ui)
,我可以看到这些值,但是如何遍历它们呢?您能帮忙吗?
<div class="input-group">
<span class="input-group-addon">choices ...</span>
<input type="text" class="form-control" placeholder="choice" name="choice" id="choice">
</div>
<div class="input-group">
<span class="input-group-addon">value of choices ...</span>
<input type="text" class="form-control" placeholder="" name="prid" id="prid">
</div>
$(function() {
$("#choice").autocomplete({
source: [{
label: "Product 1",
value: "value1",
tax: "18%"
},
// These aren't fixed. Some products have, some less.
{
label: "Product 2",
value: "value2",
tax: "24%"
}
],
minLength: 1,
delay: 0,
select: function(event, ui) {
event.preventDefault();
$('#choice').val(ui.item.label);
this.value = ui.item.label;
$('#prid').val(ui.item.tax);
// I'm stuck over here
for (var i = 0; i < ui.length; i++) {
console.log(ui[i]);
}
}
});
});
您的ui
包含以下对象
{
"item": {
"label": "Product 1",
"value": "value1",
"tax": "18%"
}
}
如果您要遍历键,则可以这样做
var uiEntries = Object.Entries(ui.item)
for (var i = 0; i < uiEntries.length; i++) {
var uiEntry = uiEntries[i];
//uiEntry[0] = The key
//uiEntry[1] = The value
console.log(uiEntry[0] + ":", uiEntry[1]);
}
或者,仅记录已知密钥
console.log("label : ", ui.item.label);
console.log("value : ", ui.item.value);
console.log("tax: ", ui.item.tax);