我必须在延迟时间(几分之一秒)后执行操作。
其实我有这段代码:
$("thead.opening").click(function () {
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
alert("INTO second function, chrome: " + is_chrome);
$(this).next().css('width', '10000000em');
$(this).next().css('display', 'table-row-group');
});
我需要做的是替换此警报():
alert("INTO second function, chrome: " + is_chrome);
等待一段时间的操作。
我该怎么做?
THX
答案 0 :(得分:2)
您可以使用纯javascript函数setTimeout
setTimeout(
function()
{
//Execute the code to be run
}, 1000);
最终解决方案
$("thead.opening").click(function () {
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
setTimeout(
function()
{
//Execute the code to be run
$(this).next().css('width', '10000000em');
$(this).next().css('display', 'table-row-group');
}, 1000);
});
答案 1 :(得分:1)
使用超时;在javascript中你可以使用setTimeout来:
在指定的延迟后调用函数或执行代码段。
像:
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
var $myNext=$(this).next();
if (is_chrome) {
window.setTimeout(function() {
$myNext.css({width: '10000000em', display: 'table-row-group'});
}, 1000);
}
演示:http://jsfiddle.net/4pxedhzd/
参考:https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
答案 2 :(得分:0)
替换
alert("INTO second function, chrome: " + is_chrome);
与
if(is_chrome) {
var that = this;
window.setTimeout(function() {
$(that).next().css({'width':'10000000em', 'display':'table-row-group'});
}, 1000);
}
这将在1000毫秒(= 1秒)后运行该函数。您必须设置that = this
,因为this
在函数中有另一个上下文。
JSFiddle演示:https://jsfiddle.net/0eajx8sv/
答案 3 :(得分:0)
我建议使用回调,而不是在代码中间使用典型的“等待”,因为这是JavaScript正常使用的。
我建议使用“setTimeout”函数让JavaScript调用等待一段特定的时间再做下一件事。以下是它在您的场景中的使用方法:
$("thead.opening").click(function () {
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
setTimout(waitedCall(), millisecondsToWait);
});
//This function will now be called after "millisecondsToWait" ms. And then execute the rest of the code
function waitedCall()
{
$(this).next().css('width', '10000000em');
$(this).next().css('display', 'table-row-group');
}