问题
I'm looking to delay running this function for 3 seconds:
<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>
The examples I've come across all involve using setTimeout to or show an element after X seconds. But I'm unsure how that would apply to my function.
回答1:
Use 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);
回答2:
You need to use setTimeout() as it is fired once on the other hand setInterval() is triggered until clear interval is called.
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
The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
setInterval
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.
回答3:
JQuery has its own .delay() function. For documentation: http://api.jquery.com/delay/
Although I'm not able to test this for myself atm. This might give you a small idea how to accomplish this.
<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>
来源:https://stackoverflow.com/questions/15951708/delay-running-a-function-for-3-seconds