html5 datalist 选中option选项后的触发事件
(编辑:jimmy 日期: 2024/11/14 浏览:3 次 )
使用input + datalist 实现自动补全功能,其中datalist中的内容是根据input输入的内容动态变换的,代码如下
<!DOCTYPE HTML> <html> <body> <script src="./jquery-1.7.2.min.js" type="text/javascript" charset="utf-8"></script> <script> function inputSelect(){ var input_select=$("#input").val(); var option_length=$("option").length; var option_id=''; for(var i=0;i<option_length;i++){ var option_value=$("option").eq(i).attr('data-value'); if(input_select==option_value){ option_id=$("option").eq(i).attr('data-id'); break; } } console.log(input_select,option_length,option_id); }; </script> <input list="cars" id="input" οnchange="inputSelect()"/> <datalist id="cars"> <option value="111" data-value="111" data-id="1"> <option value="122" data-value="122" data-id="2"> <option value="1222" data-value="1222" data-id="4"> </datalist> </body> </html>
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
下一篇:关于解决iframe标签嵌套问题的解决方法