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

查看:19
本文介绍了在链接上模拟 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?

推荐答案

你可以使用click 触发被选元素点击事件的函数.

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天全站免登陆