2013-04-11 70 views
1

我期待延緩這個函數運行3秒鐘:延遲運行一個功能3秒鐘?

<script type="text/javascript"> 
$('#FormsPageID table tr:nth-child(12) td:nth-child(2) div span span input') 
    .on('focus', function(){ 
     var $this = $(this); 
     if($this.val() == '4/11/2013'){ 
      $this.val(''); 
     } 
    }) 
    .on('blur', function(){ 
     var $this = $(this); 
     if($this.val() == ''){ 
      $this.val('4/11/2013'); 
     } 
    }); 
</script> 

我遇到的例子都涉及使用的setTimeout或X秒後顯示的元素。但我不確定這將如何適用於我的功能。

+0

你想推遲什麼?你綁定事件的部分,還是你想延遲事件的主體? – zzzzBov 2013-04-11 14:43:06

回答

3

使用的setTimeout:

setTimeout(function(){$('#FormsPageID table tr:nth-child(12) td:nth-child(2) div span span input') 
.on('focus', function(){ 
     var $this = $(this); 
     if($this.val() == '4/11/2013'){ 
      $this.val(''); 
     } 
    }) 
    .on('blur', function(){ 
     var $this = $(this); 
     if($this.val() == ''){ 
      $this.val('4/11/2013'); 
     } 
    });}, 3000); 
+0

謝謝,gabitzish!完美地工作。如果我想使用當前日期而不是2013年4月11日的值,那麼我將如何修改此值來執行此操作? – manh2244 2013-04-11 14:57:50

3

您需要使用setTimeout(),因爲它是一次燒製,另一方面setInterval()被觸發,直到明確的時間間隔被調用。

Live Demo

$('#FormsPageID table tr:nth-child(12) td:nth-child(2) div span span input') 
    .on('focus', function(){ 
    var $this = $(this); 
    if($this.val() == '4/11/2013'){ 
     setTimeout(function(){ 
      $this.val('4/11/2013'); 
     }, 3000); 
    } 
}).on('blur', function(){ 
     var $this = $(this); 
     if($this.val() == ''){ 
      setTimeout(function(){ 
      $this.val('4/11/2013'); 
      }, 3000); 
     } 
}); 

的setTimeout

的setTimeout()方法調用函數或毫秒的指定次數後計算表達式 。

的setInterval

的setInterval()方法調用函數或在指定的時間間隔計算表達式 (以毫秒爲單位)。

setInterval()方法將繼續調用該函數,直到調用clearInterval(),或者窗口關閉。

+0

不適合我。爲了澄清,我期待在頁面加載後3秒運行 - 一旦加載,onfocus和onblur不需要任何延遲。將我的所有原始代碼包裝在setTimeout函數中是否有用? – manh2244 2013-04-11 14:52:05

+0

有錯字,setTimout應該設置超時,用現場演示檢查我更新的答案。 – Adil 2013-04-11 15:05:14

+0

如果我想使用當前日期而不是2013年4月11日的值,我將如何修改此操作? – manh2244 2013-04-11 15:22:31

0

JQuery有自己的.delay()函數。 有關文檔:http://api.jquery.com/delay/

儘管我無法爲自己的atm測試此功能。這可能會給你一個小想法如何實現這一點。

<script type="text/javascript"> 
$('#FormsPageID table tr:nth-child(12) td:nth-child(2) div span span input').delay(3000).focus(function() { 
    var $this = $(this); 
    if($this.val() == '4/11/2013'){ 
     $this.val(''); 
    } 
    }).delay(3000).blur(function() { 
    var $this = $(this); 
    if($this.val() == ''){ 
     $this.val('4/11/2013'); 
    } 
    }); 
</script> 
+0

如果我想使用當前日期而不是2013年4月11日的值,那麼我會如何修改此操作? – manh2244 2013-04-11 15:10:12

+0

@ manh2244對不起,我遲到的反應。在這個主題中,你可以預覽如何檢索當前日期http://stackoverflow.com/questions/1531093/how-to-get-current-date-in-javascript只需構建日期並將其放入一個var,你會使用而不是'4/11/2013'字符串。 – larssy1 2013-04-18 13:38:29