使用input + datalist 實現(xiàn)自動補(bǔ)全功能,其中datalist中的內(nèi)容是根據(jù)input輸入的內(nèi)容動態(tài)變換的,代碼如下
<!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選項獲取對應(yīng)的屬性值.
<!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里, 然后獲取對應(yīng)的屬性data-id, firstIp, lastIp -->
測試結(jié)果如下:
當(dāng)選擇第二個選項時候, console打印出結(jié)果:
input_select:10.0.23.64~127,option_length:3
data_id:2,firstIp:63,lastIp:127
到此這篇關(guān)于html5 datalist 選中option選項后的觸發(fā)事件的文章就介紹到這了,更多相關(guān)html5 datalist 選中option 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!