事件监听

1.javascript中的事件监听:(addEventListener)

     addEventListener: 用于向指定元素添加事件.例如:

document.getElementById("inputSwitch").addEventListener("input", function() {
                $timeout(function() {
                    if ((/^\d{11}$/.test($scope.searchInfo))) {
                        console.log(1233);
                        $scope.searchState = true;
                    }else if ((/^(\d{18}|\d{19}|\d{17})$/.test($scope.searchInfo))) {
                        console.log(1237);
                        $scope.searchState = true;
                    }else{
                        $scope.searchState = false;
                    }
                }, 50)
 }, false);

 <input type="text" placeholder="输入手机号/身份证号查询"  class="seach_input" style="width:calc(100% - 300px)" id="inputSwitch" />

上述代码用于监听input值得变化;没当input输入的值发生变化时,都会调用该函数。

element.addEventListener(eventfunctionuseCapture)   ;其中第3个参数尚未理解,一般为false;

 

2.jquery中的事件监听:( bind  live  delegate  on)

    其中on监听已渐渐取代其他3种,本文主要讲解on的事件监听。

   

$('#inputSwitch').on('input oninput', function() {
                
                    if ((/^\w{11}$/.test($scope.searchInfo))) {
                        console.log(1233);
                        $scope.searchState = true;
                    } else if ((/^(\w{18}|\w{19}|\w{17})$/.test($scope.searchInfo))) 
                    {
                        console.log(1237);
                        $scope.searchState = true;
                    } else {
                        $scope.searchState = false;
                    }
                    console.log(1233)
               
            });
<input type="text" placeholder="输入手机号/身份证号查询"  class="seach_input" style="width:calc(100% - 300px)" id="inputSwitch" />

同样是上面的例子:该方法用于监听input元素中的oniput方法,当input的值发生改变时,处罚监听函数

$(selector).on(event,childSelector,data,function)    其中如需添加只运行一次的事件然后移除,请使用 one()方法;
 
3.angularJS中的事件监听:( $switch )
$scope.$watch('searchInfo',function(newValue,oldValue){
                   $timeout(function() {
                    if ((/^\w{11}$/.test(newValue))) {
                        console.log(1233);
                        $scope.searchState = true;
                    } else if ((/^(\w{18}|\w{19}|\w{17})$/.test(newValue))) {
                        console.log(1237);
                        $scope.searchState = true;
                    } else {
                        $scope.searchState = false;
                    }
                    console.log(1233)
                }, 50)
            })
<input type="text" placeholder="输入手机号/身份证号查询"  ng-model="searchInfo" class="seach_input" style="width:calc(100% - 300px)" id="inputSwitch" />

同样是上面的例子:该方法用于监听input元素值的变化(即model的变化),当input的值发生改变时,触发该函数。 其中2个参数为:一个为新输入的值,第2个为旧值。

     

posted on 2018-06-29 10:07  晓风零乱  阅读(168)  评论(0编辑  收藏  举报

导航