简体   繁体   English

在JavaScript中设置超时

[英]set time out in JavaScript

Firefox always loads dynamic images, but IE it just shows images without any dynamic action. Firefox总是加载动态图像,但是IE只是显示图像而没有任何动态动作。 what changes I need to do? 我需要做什么改变?

JavaScript code from IE view source code: IE查看源代码中的JavaScript代码:

<script type=”text/javascript”
    <!--/*--><![CDATA[/*><!--*/ 
    if (document.getElementById("safeForm1d3").submitted.value == "false") { 
      document.getElementById("safeForm1d3").submitted.value = "true"; 
      setTimeout('document.getElementById("safeForm1d3").submit()', 100); 
    }else{ 
    document.getElementById("toHide").style.display="none"; 
    }/*-->]]>*/
</script>

I am using Wicket framework, so real java code is: 我正在使用Wicket框架,所以真正的Java代码是:

 static private class SafeSubmitBehaviour extends AbstractBehavior{
    public void onRendered( Component component ) {
      super.onRendered( component );      
      StringBuffer buffer = new StringBuffer(200);
      buffer.append("<script type=\"text/javascript\" ><!--/*--><![CDATA[/*><!--*/\n");
      buffer.append("if (document.getElementById(\"").append(component.getMarkupId()).append("\").submitted.value == \"false\") {\n");
      buffer.append("document.getElementById(\"").append(component.getMarkupId()).append("\").submitted.value = \"true\";\n");
      buffer.append("setTimeout('document.getElementById(\"").append(component.getMarkupId()).append("\").submit()', 100);\n}else{\n");
      buffer.append("document.getElementById(\"toHide\").style.display=\"none\";\n}/*-->]]>*/</script>");      
      component.getResponse().write(buffer);
    }  
  } 

html page which loads my dynamic image is: 加载我的动态图像的html页面是:

<div id="toHide" class="pb-text-align-center">
        <img style="display: inline" src="img/load.gif" />
            <form wicket:id="safeForm" class="clearfix">
            <input type="hidden" wicket:id="submitted" value="false" />
        </form>
</div>

因为setTimeout()要求您的函数作为字符串或匿名函数传递:

setTimeout(function() { document.getElementById("safeFormec").submit(); }, 100);

Take away the quotes from around your action: 从您的操作中删除报价:

setTimeout(function() {
    document.getElementById("safeForm4d").submit();
}, 3000);

Have you tried removing the function call brackets from the end of this line? 您是否尝试过从此行的末尾删除函数调用括号?

document.getElementById("safeForm9c").submit()

ie do this instead: 即这样做:

setTimeout(document.getElementById("safeForm9c").submit, 100)

You're telling IE to call the results of submit() in 100 milliseconds time, rather than call submit. 您要告诉IE在100毫秒内调用Submit submit()的结果,而不是调用Submit。

Try something like this 试试这个

setTimeout(function(){document.getElementById("safeForm9c").submit();}, 100);

In the old days a setTimeout complete function was in a string format, but these days we use it this way. 在过去,setTimeout完整功能是字符串格式,但是现在我们以这种方式使用它。 Also this way makes is possible to do more things when the timeout is complete. 同样,通过这种方式可以在超时完成后做更多的事情。

尝试将它们包装在函数中:

setTimeout(function(){ document.getElementById("safeForm4d").submit(); }, 100);
function setsubmit()
{
   document.getElementById("safeFormec").submit();
}

setTimeout('setsubmit()',100);

change this 改变这个

 setTimeout(function() {
        'document.getElementById("safeForm4d").submit()'
    }, 3000);

to... 至...

 setTimeout(function() {
        document.getElementById("safeForm4d").submit()
    }, 3000);

Can you try doing something like 你可以尝试做类似的事情吗

setTimeout('document.getElementById("safeForm9c").submit()', 100);

Probably setTimeout accepts the things you want to call as a string, so that it can do an eval after the timeout and run the script as it encouters in the string. setTimeout可能以字符串的形式接受您要调用的内容,以便它可以在超时后进行评估并在字符串中封装脚本时运行脚本。

Include this in the head 包括在头上

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>

and have 并有

 static private class SafeSubmitBehaviour extends AbstractBehavior{
    public void onRendered( Component component ) {
      super.onRendered( component );      
      StringBuffer buffer = new StringBuffer(200);
      buffer.append("<script type=\"text/javascript\" >\n");
      buffer.append("var input = $(\"input[name='submitted']\");\n");
      buffer.append("if (input.val() == \"false\") {\n"); 
      buffer.append("  input.val(\"true\");\n"); 
      buffer.append("  setTimeout(function(){ $(\"#").append(component.getMarkupId()).append("\").submit()}, 100);\n"); 
      buffer.append("}\n");
      buffer.append("else {\n $(\"#toHide\").hide();\n}"); 
      component.getResponse().write(buffer);
    }  
  } 

which should render 应该渲染

var input = $("input[name='submitted']");
if (input.val() == "false") { 
  input.val("true"); 
  setTimeout(function(){ $("#safeForm1d3").submit()}, 100); 
}else{ 
  $("#toHide").hide(); 
}

Where would you do the $("#toHide").show(); 您将在哪里执行$("#toHide").show(); ?

solved my problem. 解决了我的问题。 may be useful for others: 可能对其他人有用:

Answer: 回答:

HTML source code: HTML源代码:

<SCRIPT type="text/javascript"> 
    var $ = jQuery.noConflict(); 
    document.getElementById('toHide').style.display ="";
    $('#toHide').doTimeout(1000, function() { 
        $('#toHide').find('#safeForm34').submit(); 
        document.getElementById('myAnimatedImage').src = "../../img/load.gif"; 
        });
</SCRIPT>

html: 的HTML:

  <div id="toHide" class="pb-text-align-center">
    <img src="img/load.gif" id='myAnimatedImage' style="margin-left: auto; margin-right: auto;"/>
    <form wicket:id="safeForm" class="clearfix" />
</div>

You can try: 你可以试试:

img style="display: inline" src="img/load.gif?salt=xxxx"

xxx : means - a random of an integer. xxx :表示-整数的随机数。

Maybe, the browser cache the image so it will not repaint. 也许,浏览器缓存了图像,因此它不会重新绘制。 Or you must set the GIF image with loop. 或者,您必须使用循环设置GIF图像。

I have tried with adding function call, now images are loading and dynamic, but it never goes to next page or never clear timeout. 我尝试添加函数调用,现在图像正在加载并且是动态的,但是它从未进入下一页或从未清除超时。

code: 码:

buffer.append("setTimeout(function(){'document.getElementById(\"").append(component.getMarkupId()).append("\").submit()'}, 100);\n}else{\n");
var safeForm4d = document.getElementById("safeForm4d");
if ( safeForm4d.submitted.value == "false" ){
   safeForm4d.submitted.value = "true";
   setTimeout(function(){ safeForm4d.submit(); }, 100);
}else{
   document.getElementById("toHide").style.display="none";
}

This: 这个:

setTimeout(function(){'document.getElementById("safeForm4d").submit()'}, 100);

is incorrect. 是不正确的。 The function you pass there to ".setTimeout()" will do nothing. 您在那里传递给“ .setTimeout()”的函数将无效。 Instead of that, try: 而是尝试以下方法:

setTimeout(function(){ document.getElementById("safeForm4d").submit(); }, 100);

The difference is that the actual guts of the function should not have been quoted. 所不同的是,不应引用该函数的实际内脏。 In that state, what you've got is a function with a single statement, that statement being a simple string-valued expression. 在这种状态下,您获得的是带有单个语句的函数,该语句是一个简单的字符串值表达式。 It would run, but have no effect. 它会运行,但是没有效果。

two things: 两件事情:

  1. The correct usage of setTiemout() is: setTiemout()的正确用法是:

     setTimeout(function(){ document.getElementById("safeForm4d").submit(); }, 100); 
  2. Your using wicket. 您使用的检票口。 The wicket:id is nothing the DOM knows. wicket:id是DOM所不知道的。 You have to assign an ID and use this one like you did it with the form itself. 您必须分配一个ID,然后像处理表单本身一样使用它。

Hope that helps. 希望能有所帮助。

setTimeout(function (){ document.getElementById("safeForm").submit() } , 100);

check working example at JSFIDDLE . JSFIDDLE上查看工作示例。

CAUTION :: alert may be irritating. 注意 ::警报可能会令人讨厌。

The setTimeout function throws invalid arguments because whatever the call setTimeout函数将抛出无效的参数,因为无论调用

document.getElementById("safeFormec").submit()

returns (some error message maybe) is not a valid argument to setTimeout ie it can not be resolved to a function or expression. 返回(可能是一些错误消息)不是setTimeout的有效参数,即无法将其解析为函数或表达式。

The call to .submit() fails because there is no action attribute specified for the form ( <form action="somePage.php"> ). .submit()的调用失败,因为没有为表单指定任何动作属性( <form action="somePage.php"> )。

Your intention was probably not to do a submit in the setTimeout call, but to send the submit function as a value parameter to setTimeout to be executed after a while. 您的意图可能不是在setTimeout调用中进行提交,而是将Submit函数作为值参数发送给setTimeout以便在一段时间后执行。 Like this: 像这样:

setTimeout(document.getElementById("safeFormec").submit, 100);

Note the missing paranthesises. 请注意缺少的parathethenes。

Issue was with time 100 ie 1/10 of second. 问题在于时间100,即秒的1/10。 IE will load images with dynamic action only for for 100 millisecond ie1/10 second and stop. IE将仅以100毫秒(即1/10秒)的动态动作加载图像,然后停止。 increased time to 3000 and now it is working fine. 时间增加到3000,现在工作正常。

setTimeout(function(){'document.getElementById("safeForm4d").submit()'}, 100); setTimeout(function(){'document.getElementById(“ safeForm4d”)。submit()'},100);

No issues with FF or other browser. FF或其他浏览器没有问题。

After formatting your initial post I think maybe I found some sources to the problem. 在格式化您的第一篇文章之后,我想也许我找到了问题的一些根源。

  • The function in your timeout is a string. 超时中的函数是一个字符串。
  • You should try and submit the form, not the actual button. 您应该尝试提交表单,而不是实际的按钮。

Try this: 尝试这个:

if (!document.getElementById("safeForm4d").submitted.value) {
    document.getElementById("safeForm4d").submitted.value = "true";
    setTimeout(function() {
        document.forms[0].submit(); // Alt: document.forms['MyFormName'].submit()
    }, 3000);
} else {
    document.getElementById("toHide").style.display="none";
}

This will never give you the desired effect because your changing from page to page -- this will cause the aninmation to disappear once the new page starts to load. 这将永远不会给您带来理想的效果,因为您在页面之间进行切换 –一旦新页面开始加载,这将使动画消失。 This will depend on many factors, such as how long the server takes to response, to how fast the user's computer is to re-render the new page. 这将取决于许多因素,例如服务器响应所需的时间,用户计算机重新呈现新页面的速度。

If you really want this kind of effect to work you should use ajax to send the form data using .serialize() , overwrite the current page with the response which should hide the animation. 如果您确实希望这种效果起作用,则应使用ajax通过.serialize()发送表单数据,并用.serialize()覆盖动画的响应覆盖当前页面。


Update: 更新:

To create the desired effect you'll have to post the form using ajax, then push the new HTML to the DOM. 要创建所需的效果,您必须使用ajax发布表单,然后将新的HTML推送到DOM。

var $form = $('#formId');

$.ajax({
   url: $form.attr('action'),
   type: $form.attr('method'),
   data: $form.serialize(),
   success: function(response) {
    $('#loading').fadeOut(function() {
            // Get only text from the body of the result
        $('body').html($(response).find('body'));
    });
  }
});

This is really hacky though and I felt dirty writing that. 不过,这确实很hacky,我对此写东西感到很脏。 Seriously. 说真的 You should really make sure that the response returned isn't go to: 您应该确保返回的响应不会发送到:

  • Reload CSS styles, scripts, etc. 重新加载CSS样式,脚本等。
  • Any specific title, scripts, styles, etc relevant to that page and search will not appear or be changed. 与该页面和搜索相关的任何特定标题,脚本,样式等都不会出现或更改。

More than likely you just want to return the result to the query ie the search results of the form submitted. 您很可能只想将结果返回给查询,即所提交表单的搜索结果。 In which case just wrap the results in a container and .find('#container') instead of .find('body') 在这种情况下,只需将结果包装在容器中,然后使用.find('#container')而不是.find('body')

You have quotes in the setTimeout event: setTimeout事件中有引号:

setTimeout('document.getElementById("safeForm4d").submit()', 100);

Change your script as follows: 如下更改脚本:

<script type="text/javascript">
    if (document.getElementById("safeForm4d").submitted.value == "false") {
        document.getElementById("safeForm4d").submitted.value = "true";
         if(Wicket.Browser.isIE()) {
             setTimeout(document.getElementById("safeForm4d").submit(), 100);
         } else { 
             setTimeout(document.getElementById("safeForm4d").submit(), 100);
         }
    } else {
        document.getElementById("toHide").style.display="none";
    }
</script>

Try this: 尝试这个:

<script type="text/javascript">
    if (document.getElementById("safeForm4d").submitted.value == "false") {
        document.getElementById("safeForm4d").submitted.value = "true";
        setTimeout('document.getElementById("safeForm4d").submit()', 100);
    } else {
        document.getElementById("toHide").style.display="none";
    }
</script>

Finally solved my question, may be useful for others: 终于解决了我的问题,可能对其他人有用:

Answer: 回答:

HTML source code: HTML源代码:

<SCRIPT type="text/javascript"> 
    var $ = jQuery.noConflict(); 
    document.getElementById('toHide').style.display ="";
    $('#toHide').doTimeout(1000, function() { 
        $('#toHide').find('#safeForm34').submit(); 
        document.getElementById('myAnimatedImage').src = "../../img/load.gif"; 
        });
</SCRIPT>

html: 的HTML:

  <div id="toHide" class="pb-text-align-center">
    <img src="img/load.gif" id='myAnimatedImage' style="margin-left: auto; margin-right: auto;"/>
    <form wicket:id="safeForm" class="clearfix" />
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM