jQuery事件绑定无法正常工作,或者我无法使其正常工作 [英] jQuery event binding does not work properly or i can't make it properly working

查看:141
本文介绍了jQuery事件绑定无法正常工作,或者我无法使其正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML

<input id="email" name="email" type=text />
<input id="password name="password" type="password" />

JavaScript

var fields = ["email","password"];
for (var i in fields) {
    var field = $("#"+fields[i]);
    field.bind({
        focus: function() {
            field.css("border-color","#f00");
        },
        blur: function() {
            field.css("border-color","#000");
        }
    });
}

我的渴望操作将如下所示:


  1. 当我将光标放在上述任何一个字段时,输入字段的边框将为红色。

  2. 当我将光标从字段中移除时,边框将变黑。

但事件只适用于的 b

推荐答案

这是一个真正常见的问题,字段变量在焦点上访问 blur 事件属于外层范围,所以它包含最后一个迭代值,在你的情况下它将包含密码

This is a really common problem, the field variable accessed on the focus and blur event belongs to the outer scope, so it contains the last iterated value, in your case it will contain "password".

有很多方法可以解决这个问题,例如你可以使用 $。每个引入了一个新的范围:

There are a lot of ways to solve this, for example you could use $.each which introduces a new scope:

jQuery.each(["email", "password"], function(index, fieldId) {
  var field = $('#'+fieldId);

  field.bind({
    focus: function() {
      field.css("border-color","#f00");
    },
    blur: function() {
      field.css("border-color","#000");
    }
  });
});

或使用 $(this)而不是

var fields = ["email","password"];
for (var i = 0; i < fields.length; i++) {
    $("#"+fields[i]).bind({
        focus: function() {
            $(this).css("border-color","#f00");
        },
        blur: function() {
            $(this).css("border-color","#000");
        }
    });
}

离线主题注释:也在上面的例子中,我使用一个正常的循环,而不是语句中的,这并不意味着被用于类似数组的对象。

尝试两个代码示例 here

这篇关于jQuery事件绑定无法正常工作,或者我无法使其正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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