Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2397464
  • 博文数量: 328
  • 博客积分: 4302
  • 博客等级: 上校
  • 技术积分: 5486
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-01 11:14
个人简介

悲剧,绝对的悲剧,悲剧中的悲剧。

文章分类

全部博文(328)

文章存档

2017年(6)

2016年(18)

2015年(28)

2014年(73)

2013年(62)

2012年(58)

2011年(55)

2010年(28)

分类: JavaScript

2014-02-24 13:15:25

遇到如此需求,首先想到的是change事件,但用过change的都知道只有在input失去焦点时才会触发,并不能满足实时监测的需求,比如监测用户输入字符数。

在经过查阅一番资料后,欣慰的发现firefox等现代浏览器的input有oninput这一属性,可以用三种方式使用它:

1,内嵌元素方式(属性编辑方式)

<input id="test" oninput="console.log('input');" type="text" />

2,句柄编辑方式

document.getElementById('test').oninput=function(){
    console.log('input');
}

3,事件侦听方式(jquery)

$('#test').on('input',function(){ console.log('input'); })

 

但是,以上代码仅在除了ie的浏览器大大们里才work,那ie该怎么处理呢? 在ie中有一个属性叫做onpropertychange:

<input id="test" onpropertychange="alert('change');" type="text" />

经过调试后马上就会发现,这个属性是在元素的任何属性变化时都会起作用,包括我们这里所提到的value,但至少是起作用了,那接下来的任务就是筛选出property为value的变化。

document.getElementById('test').attachEvent('onpropertychange',function(e) { if(e.propertyName!='value') return;
    $(that).trigger('input');
});

在上面代码中的回调函数中会传入一个参数,为该事件,该事件有很多属性值,搜寻一下可以发现有一个我们很关心的,叫做propertyName,也就是当前发生变化的属性名称。然后就相当简单了,只要在回调函数中判断一下是否为我们所要的value,是的话就trigger一下‘input’事件。

 

然后,就可以在主流浏览器中统一用这样的方式来监听‘input’事件了。

$('#test').on('input',function(){
    alert('input');
})

 

最后贴上完整代码:

复制代码
$('#test').on('input',function(){
    alert('input');
}) //for ie if(document.all){
    $('input[type="text"]').each(function() { var that=this; if(this.attachEvent) { this.attachEvent('onpropertychange',function(e) { if(e.propertyName!='value') return;
                $(that).trigger('input');
            });
        }
    })
}
复制代码

转载自:http://www.cnblogs.com/asie-huang/archive/2012/07/10/2585038.html
阅读(4486) | 评论(0) | 转发(3) |
给主人留下些什么吧!~~