函数在文本字段焦点上多次运行

ajs*_*sie 3 javascript jquery

我想调用一个函数,当我有一个文本域聚焦,然后不聚焦它(无论我按TAB或用鼠标点击其他地方)我使用此代码:

 $("#settings_view #my_profile_div input").focus(function() {
        $(this).blur(function() {
            change_my_profile();
        });
    });
Run Code Online (Sandbox Code Playgroud)

当我第一次运行它(有一个聚焦的场然后不聚焦它)它按预期运行一次.但是,它第二次调用函数change_my_profile两次.它第三次运行3次,依此类推.

这是什么问题,如何解决?(我在change_my_profile之后尝试'throw',然后它只运行了一次,但我想找到问题所在.)

ekh*_*led 5

blur每次启动焦点事件时它都会绑定一个事件,这就是为什么你要进行多次执行

尝试

$(this).bind("blur",function(){
  change_my_profile(this);
})
Run Code Online (Sandbox Code Playgroud)

然后在您的change_my_profile函数中执行以下操作

function change_my_profile(el){
  $(el).unbind("blur");
  //rest of the change_my_profile code goes here
}
Run Code Online (Sandbox Code Playgroud)