设置执行Javascript函数的时间?

时间:2014-08-29 12:26:04

标签: javascript jquery settimeout

我将以下函数挂钩到我的Wordpress插件中。

function before_submit() { 
    document.getElementById('page-loader').style.display='block';
}

在提交表单之前调用此挂钩。现在我想做的是在实际提交表单之前,将div id page-loader保持特定的秒数。我已经阅读了关于settimeout函数并尝试了一些东西,但我无法让它工作。我想settimeout函数是在之后运行一个脚本而不是运行 几秒钟正确吗?

所以我希望脚本具有“运行时间”,例如4秒。现在它运行脚本并立即提交表单

试过这个,但它不起作用:

function before_submit()
{

function partA() {
document.getElementById('page-loader').style.display='block';
  window.setTimeout(partB,1000)
}

function partB() {
//let's go submit the form
}
}

请帮帮我。 非常感谢你!

3 个答案:

答案 0 :(得分:1)

这是您正在寻找的格式:

// Note, in the fiddle, this is run during the window.onload event.
var test = document.getElementById('test');

test.addEventListener('submit', function before_submit(e){
    document.getElementById('wait').style.display = 'block';

    setTimeout(function wait(){
        // After waiting for five seconds, submit the form.
        test.submit();
    }, 5000);

    // Block the form from submitting.
    e.preventDefault();
});

http://jsfiddle.net/rmef40c5/

答案 1 :(得分:0)

你必须阻止默认行为,例如与<input type="button" onclick="before_submit();return false;" />

答案 2 :(得分:-1)

它可能对你有用。 首先在Click按钮上调用before_submit函数,然后为page-loader调用一个函数,然后在几秒钟后它将提交你的表单。

<form action="asd.html" method="post" id="myForm">
<input type="button" onclick="before_submit()" />
</form>

<Script>
function before_submit()
{
// document.getElementById('page-loader').style.display='block';
 setTimeout(to_submit_form,5000);
}

function to_submit_form(){
alert("submit");
 document.getElementById("myForm").submit();
}

</script>