开发者

jQuery auto click on a link

开发者 https://www.devze.com 2023-04-01 21:16 出处:网络
Ok, s开发者_运维问答o I searched all over with no answer. Can someone explain why does not work with .trigger(\'click\')

Ok, s开发者_运维问答o I searched all over with no answer. Can someone explain why

does not work with .trigger('click')

<a id="openNew" href="http://www.example.org">Click me</a>

<script type='text/javascript'> 
    $(window).load(function(){
        $('#openNew').addClass("external").attr({ target: "_blank", href: 'http://www.google.com' }).trigger('click');
    });
</script>

and it does not work with .click()

<script type='text/javascript'> 
    $(window).load(function(){
        $('#openNew').addClass("external").attr({ target: "_blank", href: 'http://www.google.com' }).click();
    });
</script>

Does not click the link whatever I do. It only works if I click it. How can I make it auto click? Working on this for about 1 hour and is driving me crazy, I know I'm must be doing something stupid.

JsFiddle for your convenience.

I wouldn't mind any other solution in plain JavaScript.


Simulating a user physically clicking the link is not possible. Since you are using target='_blank' I presume you want a new window? So you'll need to use window.open. Which popup blockers wont like.


Use elem[0].click(); instead of elem.click(); since you want to call the native click function and not just trigger the click event.

By the way: Popup blockers will prevent this from actually opening a new window (luckily).


Actually it's clicked, but not opened link.. check out here http://jsfiddle.net/H2KuF/5/

Probably you need to open new browser window with this link from JS.

here is samples I found:

function open2(url, opt){
  if (opt == 0) // current window
    window.location = url;
  else if (opt == 1) // new window
    window.open(url);
  else if (opt == 2) // background window
    {window.open(url); self.focus();}
}


Karl swedberg states here (One of the comments)

Using .trigger('click') will not trigger the native click event.

Doing the following will work:

<a id="openNew" href="http://www.example.org">Click me</a>

<script type='text/javascript'>
    $(window).load(function(){
        $('#openNew').addClass("external").attr({ target: "_blank", href: 'http://www.google.com' })[0].click();
    });
</script>

Demo here

0

精彩评论

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

关注公众号