开发者

Javascript to auto click on hyperlink

How do I javascript automatically click on a hyperlink (id is link_pag开发者_运维百科e) after 5 minutes?


doing a click in js is pretty easy:

function clickTheLink() {
    var a = document.getElementById('link_page');
    a.click();
}

you can register a startup script from server code in c#:

string script = "setTimeout(clickTheLink, 5*60*1000);";
Page.ClientScript.RegisterStartupScript(typeof(Page), "5min", script, true);

this appends a script block to the end of your html. setTimeout executes the function provided after the delay specified. delay is in ms, so 5 mins times 60 seconds * 1000 milliseconds.


If you want to trigger the onclick event handler of that link, it could work like this:

<head>
    <script type="text/javascript">
    setTimeout(function() {
        document.getElementById('link_page').onclick();
    }, 5 * 60 * 1000);
    </script>
</head>
...
<body>
    <a id="link_page" onclick="alert('test')">Test</a>
</body>

If you want to change to the location of the link after 5 minutes, you could try:

<head>
    <script type="text/javascript">
    setTimeout(function() {
        var linkUrl = document.getElementById('link_page').href;
        location.href = linkUrl;
    }, 5 * 60 * 1000);
    </script>
</head>
...
<body>
    <a id="link_page" href="http://www.google.de/">Test</a>
</body>

The key function in both methods is the setTimeout() function, which takes a callback function and a timespan in milliseconds after which the callback function is executed. More on setTimeout(): http://www.w3schools.com/js/js_timing.asp

Mind: I tested these on OSX / Firefox, so test these on PC, too.


window.onload = function () { setTimeout('document.getElementById("link_page").click()', 1000*60*5); };

?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜