要想實現(xiàn)實時監(jiān)聽input輸入框值的變化的效果难菌,只需要讓input元素監(jiān)聽兩個事件:input
和propertychange
竞惋,然后調(diào)用對應(yīng)的js監(jiān)聽函數(shù)即可柜去。
先使用原生js代碼實現(xiàn)。
<input type="text" oninput="onInputChange(event)" onpropertychange="onInputChange2(event)" />
<script type="text/javascript">
function onInputChange(event){
console.log(event.target.value);
}
function onInputChange2(event){
if(event.propertyName.toLowerCase()=="value"){
console.log(event.srcElement.value);
}
}
</script>
jQuery的實現(xiàn)代碼要比原生js簡潔很多在拆宛,這里推薦使用jQuery實現(xiàn)诡蜓。
<input type="text" id="input" />
<script type="text/javascript">
$("#input").on("input propertychange",function(event){
console.log($(this).val());
});
</script>