Submit hidden form after a delay, or immediately if a link is clicked

自古美人都是妖i 提交于 2019-12-13 00:23:48

问题


My application's session management will redirect a user to a page where the user is told their session has timed out and please <a href="path/to/page.html" id="manual_link">sign in</a>.

I'm trying to program the following behavior:

  1. If JavaScript is off (or otherwise not available), the user will have to click on the "sign in" link (POHTML; no problem).
  2. If JavaScript is running:

    a). progressively-enhance the link to instead submit the hidden form with an id of "security_redirect" (document.getElementById('manual_link').onclick = "javascript:submit_security_redirect(); return false;";)

    b) if the user does not click the link first, auto-submit the form after a 4 second delay (assume remaining_time to be 4000):

        setTimeout(function () {
            submit_security_redirect();
        }, remaining_time);
    

The four-second-delay-then-submit is happening, but I can't seem to get the link to intercept if the user doesn't want to wait four seconds. In other words, if the user clicks the link after one second...nothing happens until the four seconds are up.

I suspect I need to kill the setTimeout on link click, but don't know how (my fumbling attempts at clearTimeout were so disappointing I don't even include them in the example JSFiddle). And/or I need to prevent the a's default behavior (though I thought return false squares that away).

What modifications are necessary to achieve the desired functionality?


回答1:


You can't set onclick like that in the same way that you would set the onclick attribute in HTML -- you need to set it to a function, e.g.:

document.getElementById('manual_link').onclick = function() {
    submit_security_redirect(); return false;
};

When adding event handlers via Javascript, calling addEventListener is actually better than setting onclick, but unfortunately doesn't work in IE versions 8 and below, which is one of the reasons why cross-platform libraries like jQuery are great for event handling.

BTW, arguments.callee is deprecated (see Arguments.callee is deprecated - what should be used instead?).



来源:https://stackoverflow.com/questions/15058562/submit-hidden-form-after-a-delay-or-immediately-if-a-link-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!