简体   繁体   English

自动点击以动态添加链接

[英]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? 看来您只想前往href位置?

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() . 对于绑定动态添加的元素的事件,jQuery使用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. 因为,您需要模拟dom元素的单击。

$('#tikla').click(); will trigger the jquery click event binded to that anchor element. 将触发绑定到该锚元素的jquery click事件。 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. 谢谢大家,但没有人在Internet Explorer中工作。 I found this simple javascript works in all of the browsers. 我发现此简单的javascript在所有浏览器中均可使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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