在JQuery\JavaScript中传递一段时间(几分之一秒)之后,如何执行操作?
我必须在延迟时间(几分之一秒)后执行操作 实际上,我有这个代码部分:在JQuery\JavaScript中传递一段时间(几分之一秒)之后,如何执行操作?,javascript,jquery,html,css,jquery-timing,Javascript,Jquery,Html,Css,Jquery Timing,我必须在延迟时间(几分之一秒)后执行操作 实际上,我有这个代码部分: $("thead.opening").click(function () { var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; alert("INTO second function, chrome: " + is_chrome); $(this).next().css('width', '100
$("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');
});
我需要做的是替换此警报():
需要等待一段时间的操作
我怎么做
Thx使用超时;在javascript中,您可以使用setTimeout来: 在指定的延迟后调用函数或执行代码段 比如: 演示: 参考:更换
alert("INTO second function, chrome: " + is_chrome);
与
这将在1000毫秒(=1秒)后运行该函数。您必须设置that=this
,因为this
在函数中有另一个上下文
JSFIDLE演示:您可以使用纯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);
});
<> P>而不是在代码中间有一个典型的“等待”,我建议使用回调,因为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');
}
我会尝试,但我不想打印任何东西(我不明白:)如果您不想显示警报,只需删除它。问题是不需要执行任何操作,只需等待,然后执行上一个示例中的下一个操作。你能告诉我如何修改我以前的代码片段吗?不是downvoter,但这看起来像是MDN的复制粘贴。可能不会真正帮助提问者,因为它与问题没有明确的联系。编辑:我看到你刚刚编辑了这篇文章,在问题上看起来更“扎根”:)无视我的评论。@FabianMiiro是的,我已经改进了答案
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);
});
$("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');
}