zoukankan      html  css  js  c++  java
  • input 内容改变的触发事件【转】

    1. onchange

    onchange 事件会在域的内容改变时触发。支持的标签, , ,。

    注意:在元素的值改变了且失去焦点时触发(两次的值一样不会触发)。

    缺陷:通过js代码改变DOM的值不会触发,解决在js代码里改值了调用其change 的*function() *或者调.change()方法。

    JS:

    <input type="text" id="cc" onchange="function()">
    

    JQuery:

    $("#cc").change(function(){});
    

    2. onpropertychange

    onpropertychange会实时触发,会在元素的属性改变时就触发事件。当元素disable=true时不会触发。

    缺陷:只在IE 下支持,其他浏览器不支持,用oninput来解决。

    JS:

    <input type="text" id="cc" onpropertychange="functionName()">
    

    3. oninput

    oninput在或的值发生改变时触发,不需要等到元素失去焦点,是实时的。它是HTML5的事件,可用于检测文本类输入框的值。

    缺陷:从脚本中修改值不会触发事件。从浏览器下拉提示框里选取值时不会触发。IE9 以下不支持,所以IE9以下可用onpropertychange 事件代替。

    JS:

    <input type="text" oninput="functionName()">
    

    JQuery:

    $("#cc").on('input propertychange',functionName);
    

    4. addEventListener

    addEventListener()用于向指定元素添加事件方法。使用removeEventListener()移除添加的事件方法。IE9以下不支持,用attachEvent代替。

    语法: element.addEventListener(event, function, useCapture)

    5.jquery实时监听input输入框值的变化事件

    只需要同时绑定 oninput 和 onpropertychange 两个事件,获取input元素,并实时监听用户输入。

    $('input').bind('input propertychange', function(){
    	if($(this).val()){
    		console.log("hhhhhhhh");
    	}else{
    		console.log("xxxxxxxx");
    	}
    })
    

    但这并不完美,因为用的bind,所以当遇到追加的新input标签时,则不能监听了。

    为了解决上面的问题,可以使用live替代

    $('input').live('input propertychange', function()
    {
      //获取input 元素,并实时监听用户输入
      //逻辑
    })
    

    文章参考:
    https://www.cnblogs.com/gopark/p/10487800.html
    https://blog.csdn.net/qq_41756580/article/details/81287095

  • 相关阅读:
    Connected Graph
    Gerald and Giant Chess
    [NOI2009]诗人小G
    四边形不等式小结
    [NOI2007]货币兑换
    Cats Transport
    Cut the Sequence
    Fence
    The Battle of Chibi
    [Usaco2005 Dec]Cleaning Shifts
  • 原文地址:https://www.cnblogs.com/KillBugMe/p/12681109.html
Copyright © 2011-2022 走看看