简体   繁体   中英

Simulate the user clicking on a link

I want a link to be clicked when a key is pressed, I cooked up this jQuery:

   $('form#form1').bind("keypress", function(e){
        if(e.keycode == 13 || e.keyChar == 13 || e.which == 13){
        $('.LoginBoxButton a').click();
        }   
    });

It doesn't work, and I've read the following explaining why:

It's important to remember that click() will not trigger the default behavior on a link, even if nothing else is preventing it. So you can't use click() by itself to simulate the user clicking on a link and being taken to another url.

But how DO you simulate the user clicking on a link and being taken to another url?

You may go about like this:

$('form#form1').bind("keypress", function(e){
    if(e.keycode == 13 || e.keyChar == 13 || e.which == 13){
      document.location.href = $('.LoginBoxButton a').attr('href');
    }   
});

But how DO you simulate the user clicking on a link and being taken to another url?

These are two different things:

The first, simulate user clicking, is a quite low-level task. I'd choke to a browser that allowed it without limits.

The second, taking the user to another url, is as easy as assigning the url you want to document.location.href .

So, instead of

$('.LoginBoxButton a').click();

use

document.location.href = $('.LoginBoxButton a').attr('href');

Hope this helps.

First of all jQuery's Event.which normalizes event.keyCode and event.charCode - so you don't have to check keyCode / charCode .
Secondly decide whether you want to simulate user click on element or just redirect to other location, because there is a huge difference between one and the second. While the last one just redirect the first one first execute all connected mousedown / mouseup / click (in given order) events. Also if click event will return false redirection should be blocked.

So the code for the first situation is already given, but here's the code for true simulation:

<a href="test.html">LsINK</a>
<span>ROBOT</span>

$("a").mousedown(function() { alert("mousedown"); })
      .mouseup(function() { alert("mouseup"); })
      .click(function() { alert("click"); return false; });

$("span").click(function() {
    if (false !== $("a").mousedown().mouseup().triggerHandler("click")) {
        alert("Redirect to: " + $("a").attr("href"));
        //window.location.href = $("a").attr("href");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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