jsp中输入框值变化的监听

来源:互联网 发布:squid 监听多个端口 编辑:程序博客网 时间:2024/05/16 08:10
在 Web 开发中经常会碰到需要动态监听输入框值变化的情况,如果使用 onkeydown、onkeypress、onkeyup 这个几个键盘事件来监测的话,监听不了右键的复制、剪贴和粘贴这些操作,处理组合快捷键也很麻烦。因此这篇文章向大家介绍一种完美的解决方案:结合 HTML5 标准事件 oninput 和 IE 专属事件 onpropertychange 事件来监听输入框值变化。


 oninput 是 HTML5 的标准事件,对于检测 textarea, input:text, input:password 和 input:search 这几个元素通过用户界面发生的内容变化非常有用,在内容修改后立即被触发,不像 onchange 事件需要失去焦点才触发。oninput 事件在主流浏览器的兼容情况如下:


 <head>
    <script type="text/javascript">
    // Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9
        function OnInput (event) {
            alert ("The new content: " + event.target.value);
        }
    // Internet Explorer
        function OnPropChanged (event) {
            if (event.propertyName.toLowerCase () == "value") {
                alert ("The new content: " + event.srcElement.value);
            }
        }
    </script>
</head>
<body>
    Please modify the contents of the text field.
    <input type="text" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" value="Text field" />
</body>




$('textarea').bind('input propertychange', function() {
    $('.msg').html($(this).val().length + ' characters');
});




$('textarea').bind('input propertychange', function() {
    $('.msg').html($(this).val().length + ' characters');
});
原创粉丝点击