在链接上模拟jQuery / JavaScript中的单击 [英] Simulating a click in jQuery/JavaScript on a link

查看:125
本文介绍了在链接上模拟jQuery / JavaScript中的单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JavaScript模拟页面上任何链接的点击。如果该链接具有与其onclick事件绑定的某些功能(由任何其他JS我没有任何控制),则必须调用该函数,否则链接应以正常方式运行并打开新页面。

I want to simulate a click on any link on a page using JavaScript. If that link has some function binded to its 'onclick' event (by any other JS I don't have any control over), then that function must be called otherwise the link should behave in the normal manner and open a new page.

我不确定只检查'onclick'处理程序的值就足够了。我想构建它,以便它适用于任何链接元素。

I am not sure that just checking the value of the 'onclick' handler would suffice. I want to build this so that it works on any link element.

我无法使用任何JS库(不一定是jQuery)或只使用JavaScript来控制绑定到链接的onclick事件的函数。

I have no control over what function maybe binded to the onclick event of the link using whichever JS library (not necessarily jQuery) or by simply using JavaScript.

编辑:在下面的答案的帮助下,看起来可以检查使用jQuery附加的事件处理程序或使用 onclick 属性。如何检查使用 addEventListener /任何其他JS库附加的事件处理程序,以便它是万无一失的?

With the help of the answers below, it looks like it is possible to check for event handlers attached using jQuery or using the onclick attribute. How do I check for event handlers attached using addEventListener / any other JS library so that it is foolproof?

推荐答案

您可以使用点击功能触发点击事件在所选元素上。

You can use the the click function to trigger the click event on the selected element.

示例:

$( 'selector for your link' ).click ();

您可以在jQuery的文档

You can learn about various selectors in jQuery's documentation.

编辑:像下面的评论者所说的那样;这仅适用于使用jQuery,内联或element.onclick样式附加的事件。它不适用于addEventListener,如果没有定义事件处理程序,它将不会跟随链接。
您可以通过以下方式解决此问题:

like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:

var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
    document.location = linkEl.attr ( 'href' );
} else {
    linkEl.click ();
}

虽然不知道addEventListener。

Don't know about addEventListener though.

这篇关于在链接上模拟jQuery / JavaScript中的单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆