简体   繁体   中英

Auto click to dynamically added link

I want to auto click to the dynamically added link. Here is my script

document.write("<a id='tikla' href='http://www.example.org'>tikla</a>");

$('#tikla').click();

However it doesn't work, because of the link is dynamically added object. What is the correct way to do that ?

What are you trying to do? It looks like you just want to go to the href location?

If that's the case you can just go

window.location.href = 'http://www.example.org';

You need to add click handler before you trigger click event

Live Demo

document.write("<a id='tikla' href='http://www.example.org'>tikla</a>");

$('#tikla').click(function(){
     alert("clicked");
});

$('#tikla').click();

For binding events for elements added dynamcially jQuery provides event delegation using jQuery on() .

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

$( "#staticparent" ).on( "click", "#tikla", function() {
  alert("clicked");
});

Use

$('#tikla').get(0).click();

Because, you need to emulate the dom element click.

$('#tikla').click(); will trigger the jquery click event binded to that anchor element. In your case there is nothing binded to the anchor element.

Fiddle

You can try it like this also...

 document.write("<a id='tikla' href='http://www.example.org'>tikla</a>"); window.location.href = $('#tikla').attr('href'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 

Try this,

$("<a id='tikla' href='http://www.example.org'>tikla</a>")
    .appendTo('body') // appendto body
    .get(0).click(); // triggering click to itself

 $("<a id='tikla' href='http://www.example.org'>tikla</a>") .appendTo('body') .get(0).click(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

var myLink = document.getElementById('tikla');
myLink.click();

Thanks for all you guys, but none worked in Internet Explorer. I found this simple javascript works in all of the browsers.

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