动态文本框id分配给focusout函数


$(document).ready(function(){
var CurrentTextBoxID = "";
var shifton = false;
var IsCapsLockOn = false;   
// toggles the keyboard to show or hide when link is clicked
$(":text").focus(function(e) {              
    CurrentTextBoxID = this.id;
    var top = ($(window).height() - $('#keyboard').height()) - 25;        
    var left = ($(window).width() - $('#keyboard').width()) / 2;
    alert(CurrentTextBoxID + " focus In");
    $('#keyboard').css(
        {               
            "left": left+"px",
            "top": top+"px"
        }
    ).toggle();
});
$('#'+CurrentTextBoxID).blur(function() {
    alert("**");
});

$('#'+CurrentTextBoxID).focusout(function() {
    alert(this.id + " focus out");
});

在上面的代码中,模糊函数和聚焦函数不起作用。当我这样修改代码时,它就可以工作了。

$('#txtTest1').blur(function() {
    alert("**");
});

$('#txtTest1').focusout(function() {
    alert(this.id + " focus out");
});

但是通过改变这样的代码,我不能动态地给出文本框ID。所以,请让我知道我怎样才能做到这一点。

$( DYNAMIC ID ).focusout(function() { .... });

blur()focusout()移动到定义了CurrentTextBoxIDfocus()中。这对我来说似乎有点粗俗。

最好的方法是在动态添加事件时将事件绑定到textbox。在这种情况下,我将使用live()方式绑定您的事件。下面的代码可以工作,但是每次textbox获得focus时,它都会绑定一个事件。

CurrentTextBoxIDundefined你做的方式,你可以这样做,但更好的例子后面。

$(":text").focus(function(e) {              
    CurrentTextBoxID = this.id;
    var top = ($(window).height() - $('#keyboard').height()) - 25;        
    var left = ($(window).width() - $('#keyboard').width()) / 2;
    alert(CurrentTextBoxID + " focus In");
    $('#keyboard').css(
        {               
            "left": left+"px",
            "top": top+"px"
        }
    ).toggle();
    $('#'+CurrentTextBoxID).blur(function() {
       alert("**");
    });

    $('#'+CurrentTextBoxID).focusout(function() {
       alert(this.id + " focus out");
    });

});

或者你可以使用live()绑定文本框

$('.dynamicTextBox').live('blur', function(){
   alert("**");
});

甚至…

$(':text').blur(function(){
   alert("**" + $(this).attr('id'));
});
$(':text').focusout(function(){
   alert("**" + $(this).attr('id'));
});

因为我觉得您需要为所有文本框绑定那些blurfocusout函数。如果你在focus中一个接一个地执行(如@Gabe的答案)函数,你将在下一次focus事件发生时再次绑定该函数。
我认为你需要这样做,

$(":text").blur(function() {
    alert("**");
    var element=$(this); // you can get the element here
});

$(":text").focusout(function() {
    alert(this.id + " focus out");
});

最新更新