从 datalist
中选择一个选项后,我希望这段 javascript 代码返回 javascript object
中的 option
位置。
如果不使用datalist
,代码将按预期工作。
为什么这不起作用?
Javascript
能否响应来自 datalist
的新输入,而无需重新加载某种页面?我希望这不需要 PHP
。
var input = document.getElementById("myInputId");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function result() {
document.getElementById("location").innerHTML = input.value;
}
myObj = {
"type":"A",
"info": [
{ "item":"1", "properties":{ "id":"AL", "height": "25", width: "50" } },
{ "item":"2", "properties":{ "id":"PO", "height": "30", width: "40" } },
{ "item":"3", "properties":{ "id":"RA", "height": "20", width: "100" } }
]
}
myObj.info.forEach(function(e, z) {
var q = document.getElementById("location").innerHTML;
if (e.properties.id == q) {
document.getElementById("position").innerHTML = z;
document.getElementById("width").innerHTML = myObj.info[z].properties.width;
}
});
<input list="myInput" id="myInputId" value="">
<button id="myButton" onClick="result()">submit</button>
<datalist id="myInput">
<option>AL</option>
<option>PO</option>
<option>RA</option>
</datalist>
<p>Result:<span id="location"></span></p>
<p>Position in object:<span id="position"></span></p>
<p>Width:<span id="width"></span></p>
最佳答案
您可以使用.find()查找所选元素,然后将值分配给右侧的 html
元素:
var input = document.getElementById("myInputId");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function result() {
var res = myObj.info.find(({properties}) =>
properties.id === myInputId.value
);
/*
// you can also use .forEach()
var res;
myObj.info.forEach(e => {
if(e.properties.id === myInputId.value)
res = e;
});
*/
if(res){
document.getElementById("location").innerHTML = res.properties.id;
document.getElementById("width").innerHTML = res.properties.width;
document.getElementById("position").innerHTML = res.item;
}
}
myObj = {
"type":"A",
"info": [
{ "item":"1", "properties":{ "id":"AL", "height": "25", width: "50" } },
{ "item":"2", "properties":{ "id":"PO", "height": "30", width: "40" } },
{ "item":"3", "properties":{ "id":"RA", "height": "20", width: "100" } }
]
}
/*
myObj.info.forEach(function(e, z) {
var q = document.getElementById("location").innerHTML;
if (e.properties.id == q) {
document.getElementById("position").innerHTML = z;
document.getElementById("width").innerHTML = myObj.info[z].properties.width;
}
});
*/
<input list="myInput" id="myInputId" value="">
<button id="myButton" onClick="result()">submit</button>
<datalist id="myInput">
<option>AL</option>
<option>PO</option>
<option>RA</option>
</datalist>
<p>Result:<span id="location"></span></p>
<p>Position in object:<span id="position"></span></p>
<p>Width:<span id="width"></span></p>
关于javascript - 如何使用数据列表返回 javascript 对象中值的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51180999/