简体   繁体   English

为什么我的jquery .each()函数无法正常工作?

[英]Why is my jquery .each() function not working properly?

I wrote this function: 我写了这个函数:

jQuery(document).ready(function() {
    jQuery('input[type=text]').each( function(i) {
        thisval = jQuery(this).val();

        jQuery(this).blur( function() {
            if (jQuery(this).val() == '') {
                jQuery(this).val(thisval);
            }
        }); // end blur function
        jQuery(this).focus( function() {
            if (jQuery(this).val() == thisval) {
                jQuery(this).val('');
            };
        });// end focus function
    }); //END each function
}); // END document ready function

It's designed to get the value of an input, then if the user clicks away without entering a new value, the old value returns. 它旨在获取输入的值,然后如果用户点击而不输入新值,则返回旧值。 This works properly with one of the inputs on the page, but not the others. 这适用于页面上的一个输入,但不适用于其他输入。 However, when I remove the .blur and .focus functions and just use alert(thisval); 但是,当我删除.blur和.focus函数并只使用alert(thisval); it alerts the name of each input, so something is wrong with my function, but I can't figure out what. 它警告每个输入的名称,所以我的功能有问题,但我无法弄清楚是什么。 Any help? 有帮助吗?

You need var when declaring your variable so it's not a global one being shared, like this: 在声明变量时需要var ,因此它不是共享的全局变量,如下所示:

var thisval = jQuery(this).val();

Also since you're dealing specifically with text inputs you can just use the .value DOM property, like this: 此外,由于您专门处理文本输入,您可以使用.value DOM属性,如下所示:

jQuery(function() {
  jQuery('input[type=text]').each(function(i) {
    var thisval = this.value;
    jQuery(this).blur( function() {
        if (this.value == '') this.value = thisval;
    }).focus( function() {
        if (this.value == thisval) this.value = '';
    });
  });
});

thisval is a global variable so it is replaced with each loop. thisval是一个全局变量,因此它被每个循环替换。 Make it local [stick var in front of it] and it should work like magic. 让它本地[在它前面的变量]它应该像魔术一样工作。

You should not just keep creating jQuery(this) over and over again. 你不应该一遍又一遍地继续创建jQuery(this)。 That is very inefficient. 这是非常低效的。 jQuery(this) is expensive. jQuery(这个)很贵。 You should store one copy in a variable and use the variable. 您应该将一个副本存储在变量中并使用该变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM