jQuery每个函数都使用最后一个对象

时间:2014-04-18 04:34:47

标签: jquery each

此脚本仅适用于最后一个textarea对象:

$('textarea[data-placeholder]').each(function () {
    var $this = $(this);
    $placeholder = $this.attr('data-placeholder');
    $placeholder = $placeholder.replace(/\<br>/g, "\n");
    $informer_id = $this.attr('data-informer-link');
    console.log('each: ' + $informer_id + ', placeholder: ' + $placeholder);

    $this.attr('value', $placeholder);

    $this.focus(function () {
        if ($this.val() == $placeholder) {
            $this.attr('value', '');
        }
    });
    $this.blur(function () {
        if ($this.val() == '') {
            $this.attr('value', $placeholder);
            console.log('each brur placeholder: ' + $informer_id);
            $('[data-informer-id=' + $informer_id + '] i.fa')
                .addClass('fa-circle')
                .removeClass('fa-check-circle');
        } else {
            console.log('each brur value: ' + $informer_id);
            $('[data-informer-id=' + $informer_id + '] i.fa')
                .removeClass('fa-circle')
                .addClass('fa-check-circle');
        }
    });

    // remove the focus, if it is on by default
    $this.blur();
    $('[data-informer-id=' + $informer_id + '] i.fa')
        .addClass('fa-circle')
        .removeClass('fa-check-circle');
});

如果我抓住var $this = $(this);的对象,为什么会这样?

实例: http://jsfiddle.net/ynts/M9pZN/

1 个答案:

答案 0 :(得分:4)

问题在于你的变量。您错过了关键字var,因此您的变量是全局的

var $placeholder = $this.attr('data-placeholder');
$placeholder = $placeholder.replace(/\<br>/g, "\n");
var $informer_id = $this.attr('data-informer-link');

upd:删除了不必要的var