gpt4 book ai didi

javascript - 从数据列表中的选定选项中获取自定义属性

转载 作者:行者123 更新时间:2023-12-04 08:53:46 25 4
gpt4 key购买 nike

当我从数据列表中选择一个选项时,我想获取其自定义属性“位置”并打印它。我知道 select 有 selectedIndex 但我如何使用 datalist 完成此操作?

<!DOCTYPE html>
<html>
<body>

<input type="text" id="StartingAddressField" size="50" placeholder="Select item from list" list="select">
<datalist id="select" style="display:none;" onchange="Select1Changed();">
<option value="one" location="3"/>
<option value="two" location="15"/>
<option value="three" location="27"/>
</datalist>
</body>
</html>

最佳答案

通过使用 document.getElementById 选择元素您收到 HTMLCollection您可以迭代(在您的情况下为选项列表)并使用附加到每个元素的属性对象找到所需的属性。
我还发现,如果需要,一旦选择了值,datalist 将不可用,否则您可以查看该错误。

function Select1Changed(elem) {
let location = 'please select a valid option';
let dt = document.getElementById('select');
// dt contains a HTMLCollection of options so use for loop to iterate it use childElementCount to get the length if loop
for (let i = 0; i < dt.childElementCount; i++) {
// check the selected value with option values.
if (dt.children[i].attributes.value.value === elem.value) {
// if Hit use the attributes object to find your attribute and get its value.
location = dt.children[i].attributes.location.value;
}
}
alert(location);
}
<!DOCTYPE html>
<html>

<body>

<input type="text" id="StartingAddressField" size="50" placeholder="Select item from list" list="select" onchange="Select1Changed(this);">
<datalist id="select" style="display:none;">
<option value="one" location="3"/>
<option value="two" location="15"/>
<option value="three" location="27"/>
</datalist>
</body>

</html>

关于javascript - 从数据列表中的选定选项中获取自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63953249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com