2014-04-18 78 views
2

這個腳本部分僅適用於最後textarea對象:jQuery的每個函數使用的最後一個對象

$('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/

回答

4

的問題是在你的變量。你已經錯過了關鍵字var所以你的變量是全球

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

UPD:不必要的變種刪除

相關問題