1
$('#firstname').bind('focusout focusin', function() {
    var get_firstname = $("#firstname").val().replace(/ /g, "+");
    var n_firstname = get_firstname.length;
    if (n_firstname > 2) {
        $(".firstname_good").fadeIn("fast");
        var firstname_v = 1;
    }
    else {
        $(".firstname_good").fadeOut("fast");
        var firstname_v = '';
    }
});​

我无法理解如何使用下面的 VAR firstname_v。我需要在上面做什么才能在下面使用它

$('#lastname').bind('focusout focusin', function() {
    if (firstname_v == 1) {
        alert(firstname_v);
    }
});​
4

4 回答 4

2

您需要在两个内部范围都可以访问的更高范围内声明变量:

var firstname_v; // declare it

$('#firstname').bind('focusout focusin', function() {
    var get_firstname = $("#firstname").val().replace(/ /g, "+");
    var n_firstname = get_firstname.length;
    if (n_firstname > 2) {
        $(".firstname_good").fadeIn("fast");
        firstname_v = 1; // no var here, you're just setting it
    }
    else {
        $(".firstname_good").fadeOut("fast");
        firstname_v = ''; // no var here, you're just setting it
    }
});​

$('#lastname').bind('focusout focusin', function() {
    if (firstname_v == 1) { // no var here, you're just getting it
        alert(firstname_v);
    }
});​
于 2012-07-13T18:53:02.600 回答
1

问题是您的变量是回调函数的本地变量。

像这样在外面声明它:

   var firstname_v = '';

   $('#firstname').bind('focusout focusin', function() {
    var get_firstname = $("#firstname").val().replace(/ /g, "+");
    var n_firstname = get_firstname.length;
    if (n_firstname > 2) {
        $(".firstname_good").fadeIn("fast");
        firstname_v = 1;
    }
    else {
        $(".firstname_good").fadeOut("fast");
    }
});​
于 2012-07-13T18:50:34.893 回答
1

将顶部块更改为:

var firstname_v;
$('#firstname').bind('focusout focusin', function() {
    var get_firstname = $("#firstname").val().replace(/ /g, "+");
    var n_firstname = get_firstname.length;
    if (n_firstname > 2) {
        $(".firstname_good").fadeIn("fast");
        firstname_v = 1;
    }
    else {
        $(".firstname_good").fadeOut("fast");
        firstname_v = '';
    }
});​

请注意,唯一真正的变化是声明firstname_v现在在函数外部而不是内部完成。这是它将在您的整个代码中可用。

于 2012-07-13T18:51:57.437 回答
0

做这个:

var firstname_v = 0;

$('#firstname').bind('focusout focusin', function() {
    var get_firstname = $("#firstname").val().replace(/ /g,"+");
    var n_firstname = get_firstname.length;

    if (n_firstname > 2) {  
        $(".firstname_good").fadeIn("fast"); 
        firstname_v = 1; 
    } else { 
        $(".firstname_good").fadeOut("fast"); 
    }
});

$('#lastname').bind('focusout focusin', function() {
    if (firstname_v == 1) {
        alert(firstname_v);
    }
});​
于 2012-07-13T18:51:38.980 回答