参考博客: https://blog.csdn.net/qishuixian/article/details/78427951
最近一段时间用到了html5中datalist, 对选择的option选项获取对应的属性值.
<!DOCTYPE HTML> <html> <body> <script src="jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> function inputSelect(){ var input_select = $("#input").val(); var after_value = input_select.split("."); var new_value = after_value[0] + "." + after_value[1] + "." + after_value[2] + ".xxx"; $("#input").val(new_value); var option_length = $("#netsegments").find("option").length; var data_id = ''; var firstIp = 1; var lastIp = 255; for(var i = 0; i < option_length; i++){ var option_value = $("option").eq(i).attr('data-value'); if(input_select == option_value){ data_id = $("option").eq(i).attr('data-id'); firstIp = $("option").eq(i).attr('firstIp'); lastIp = $("option").eq(i).attr('lastIp'); break; } } console.log("input_select:" + input_select + ",option_length:" + option_length); console.log("data_id:" + data_id + ",firstIp:" + firstIp + ",lastIp:" + lastIp); };</script> <input list="netsegments" id="input" onchange="inputSelect()" placeholder="xxx.xxx.xxx.xxx" /> <datalist id="netsegments"> <option label="10.0.23.xxx" value="10.0.23.1~62" data-value="10.0.23.1~62" data-id="1" firstIp="1" lastIp="62" /> <option label="10.0.23.xxx" value="10.0.23.64~127" data-value="10.0.23.64~127" data-id="2" firstIp="63" lastIp="127" /> <option label="10.0.23.xxx" value="10.0.23.129~192" data-value="10.0.23.129~192" data-id="3" firstIp="129" lastIp="192" /> </datalist> </body> </html>
<!-- 选择option的value, 显示在input里, 然后获取对应的属性data-id, firstIp, lastIp -->测试结果如下: 当选择第二个选项时候, console打印出结果:
input_select:10.0.23.64~127,option_length:3
data_id:2,firstIp:63,lastIp:127
来源:https://www.cnblogs.com/xumBlog/p/10931989.html