IE中占位符触发jQuery输入事件 [英] jQuery input event fired on placeholder in IE

查看:106
本文介绍了IE中占位符触发jQuery输入事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段,它绑定了一个 input 事件(通过jQuery)。每次输入值更改时都应该触发此事件。我添加了一个占位符来告诉用户这个输入字段是什么。

如果用户点击此输入字段,则不应触发事件输入事件改变;只是占位符消失)。它可以在Firefox或Chrome中正常工作,但不会在IE中使用。



如何避免这种情况?



jsfiddler 上更好地理解我的问题

解决方案

防止出现问题的一种方法是,在您执行 之前,存储字段的旧值并检查它, > input 处理程序。这是我在一个应用程序中修复它的方式。



例如:

  $(document).ready(function(){
var $ input = $(#input);
var $ msg = $(#msg);
var old_value = $ input.val();
$ input.on(input,function(){
var new_value = $ input.val();
if(new_value! == old_value){
//当字段*真*改变时我们想要执行的实际工作
$ msg.text(new_value.length);
old_value = new_value;
}
});
});

这可以防止字段没有变化时的动作。


I have an input field with an input event bound to it (via jQuery). This event should be fired everytime the input value changes. I added a placeholder to tell the user what this input field is for.

If the user clicks on this input field the input event should NOT be fired (the value actually doesn't change; just the placeholder disappears). It works fine in Firefox or Chrome but not in IE.

How can I avoid this behavior?

For better understanding my problem on jsfiddler

解决方案

One way to guard against the problem is by storing the old value of your field and checking against it before performing the real function you want to perform in your input handler. This is how I fixed it in one of my applications.

For instance:

$(document).ready(function () {
    var $input = $("#input");
    var $msg = $("#msg");
    var old_value = $input.val();
    $input.on("input", function () {
        var new_value = $input.val();
        if (new_value !== old_value) {
            // The actual work we want to perform when the field *really* changes.
            $msg.text(new_value.length);
            old_value = new_value;
        }
    });
});

This prevents acting when the field is not changing.

这篇关于IE中占位符触发jQuery输入事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆