2014-06-15 164 views
2

我正在使用Jquery刪除焦點上HTML輸入的默認值。在兩個Javascript/Jquery函數之間傳遞var?

但是,如果沒有輸入到輸入中,我希望默認值重新出現。

嘗試做這個,我已經創造:

$("#contact input").each(function(index) { 

     $(this).focus(function() { 
      var valvalue = $(this).val(); 
      $(this).val(''); 
     }); 

     $(this).focusout(function() { 
      var newvalvalue = $(this).val(); 
      if(newvalvalue == ''){ 
       $(this).val('', valvalue); 
      } 
     }); 

    }); 

focus()功能工作正常,但變量valvalue沒有得到由focusout功能回升。

有人會知道一種方法將valvalue變量傳遞給第二個focusout函數嗎?

+1

製作'valvalue'全球兩個事件處理程序 – Diode

+1

當然不是「全局」 ... – user2864740

+0

http://stackoverflow.com/questions/500431/javascript-variable-scope – user2864740

回答

4

您需要使兩個事件處理程序都可以使用varvalue。可以通過將其聲明在範圍之外來完成。

$("#contact input").each(function(index) { 

    var valvalue; /* both event handlers can see it here */ 

    $(this).focus(function() { 
     valvalue = $(this).val(); 
     $(this).val(''); 
    }); 

    $(this).focusout(function() { 
     var newvalvalue = $(this).val(); 
     if(newvalvalue == ''){ 
      $(this).val('', valvalue); 
     } 
    });  

}); 
+0

謝謝,但犯規,僅僅意味着focusout函數只會得到一個空白的valvalue(即不是在第一個焦點函數中獲得的值)? – MeltingDog

+0

沒有「關注」沒有「聚焦」:) – Diode

1

你在關閉JS的問題。嘗試在函數外部定義varvalue,這樣兩個函數都引用相同的變量。

$("#contact input").each(function(index) { 
     var valvalue; 
     $(this).focus(function() { 
      valvalue = $(this).val(); 
      $(this).val(''); 
     }); 

     $(this).focusout(function() { 
      var newvalvalue = $(this).val(); 
      if(newvalvalue == ''){ 
       $(this).val('', valvalue); 
      } 
     }); 

    }); 
1

除了其他的答案,你可以利用現有的placeholder財產HTML5,如果你不希望支持舊的瀏覽器。

<input type="text" name="name" placeholder="Enter here">