开发者

Function run multiple times on textfield focus

I want to call a function when I have a textfield focused and then unfocus it (whether I press TAB or click elsewhere with the mouse) and I used this code:

 $("#settings_view #my_profile_div input").focus(function() {
        $(this).blur(function() {
            change_my_profile();
        });
    });

When I first run it (have a field focused then unfocus it) it runs one time as expected. However, the second time it calls the function change_my_profile twice. The third time it ran 3 times and so on.

What is the problem here and how do I solve it? (I tried with 'throw' after change_my_profile and then开发者_如何学Go it only ran one time, but I want to locate the problem anyway).


it is binding a blur event every time a focus event is initiated, that's why you are getting multiple executions

try

$(this).bind("blur",function(){
  change_my_profile(this);
})

and then in your change_my_profile function do the following

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


The .focus() and .blur() functions assign handlers to the 'focus' and 'blur' events repsectively. So every time the user focuses the textbox, your code is adding a new event handler to the 'blur' event. What you want is:

$("#settings_view #my_profile_div input").blur(change_my_profile);


You need to remove the event handler after successful execution. Otherwise, you are stacking handler upon handler and they all get triggered. I think in JQuery that is done using unbind()


Your code is asking jQuery to add (append) an onBlur event handler to an input field every time the user enters the field. So, your same event handler function gets appended over and over again. Are you simply trying to trigger a function to run when the user moves out of a field? If that is the case, you can simply use .blur to attach the onBlur handler once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜