onpropertychange and oninput事件

来源:互联网 发布:拉长腿的软件 编辑:程序博客网 时间:2024/05/20 06:29

 上一周的工作是做一个javascript的应用,其中一个小功能是根据用户输入的列车(火车)类型来动态的生成票价的文本输入框(text input),当时的第一印象是在用户输入列车(火车)车次时通过onkeyup或onblur事件中获取车次号,然后判断是D字头,Z字头或其他类型,然后通过Dom或插入innerHTML来生成票价的输入框。不过为了让用户体验更加友好开始寻觅一个更好的实现方式。

       在以前修改其他人的代码的时候曾经用到过onpropertychange和oninput时间,onpropertychange(oninput是IE下的事件)能够捕捉每次的键盘输入,在写了个小的demo

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>onpropertychange and oninput demo</title>
<script type="text/javascript">
<!--
function outputtodiv() {
document.getElementById("output").innerHTML = document.getElementById("input").value;
}
-->
</script>
</head>
<body>
<div id="output"></div>
<input type="text" name="input" id="input" onpropertychange="outputtodiv();" oninput="outputtodiv();" />
</body>
</html>

测试通过后决定了通过这种方法来实现。

相关代码如下:

function changeTrainType() {
    var traintypeStr = "-DZ";
    var strInput = document.getElementById("trainid").value;
    if(strInput && strInput != "") {
        var firstChar = strInput.substr(0, 1).toUpperCase();
        if(traintypeStr.indexOf(firstChar) == -1) {
            firstChar = "O";
        }  
        if(firstChar == "D") {
            document.getElementById("zhekou").disabled = false;
            document.getElementById("zhekouspan").style.color = "";
        } else {
            document.getElementById("zhekou").disabled = true;
            document.getElementById("zhekouspan").style.color = "#999";
        }  
        var seatArr = traintype_seat[firstChar];
        var priceHTML = '';
        for(var i = 0; i < seatArr.length; i ++) {
            priceHTML += seatArr[i] + ' <input class="input_2" seattype="' + seatArr[i] + '" name="price" type="text" />元&nb
sp;';
        }  
        document.getElementById("hcptc_price").style.visibility = "visible";
        document.getElementById("hcptc_price").innerHTML = "票价(全价):" + priceHTML;
    } else {
        document.getElementById("zhekou").disabled = true;
        document.getElementById("zhekouspan").style.color = "#999";
    }  
}

一切都很顺利,在Firefox测试成功时,在IE下测试该功能发现无论如何也不能正常的取回input的value,开始认为是FireFox和IE在dom接口的差异,在仔细的review代码后没有发现可疑的地方,万般无奈下将onpropertychange(oninput)属性替换为onblur后在进行测试,一切如同没电的闹钟换了电池一样的跑了起来,至此总结在应用非常见事件时一定要十分小心,以免花费大量时间来调试!

原创粉丝点击