首页 > 解决方案 > 如何在 Jquery 中使用 .click() 单击超链接?

问题描述

我正在尝试阅读一篇文章,但我厌倦了按超链接“下一页”并尝试运行下面的代码。

代码是什么 按回车会找到类“x-hidden-focus”的超链接)并单击它。

下面编写的代码通过在按下另一个网页的 enterKey 时单击一个按钮来工作,但它不适用于超链接。我尝试运行注释的代码,但两个代码都没有解决我的问题。

我要按的超链接的类是“.x-hidden-focus”

这是文章的链接

$(document).keypress(function(event){
var which = (event.which ? event.which : event.keyCode);
if(which == '13'){
    //$(".x-hidden-focus")[0].click();
    $(".x-hidden-focus").click();
}
});

注意:我将此代码用作 Tampermonkey 中的用户脚本(希望这会有所帮助)。

标签: javascriptjqueryuserscripts

解决方案


您可以尝试简单地导航到您尝试单击的链接所描述的 href:

document.location = $("a.x-hidden-focus").attr("href")

您的代码将变为:

$(document).keypress(function(event){
    var which = (event.which ? event.which : event.keyCode);
    if(which == '13'){
        document.location = $("a.x-hidden-focus").attr("href");
    }
});

根据您提供的文章,我们可以看到您尝试单击的按钮的 html 如下:

<a href="adding-a-controller" data-linktype="relative-path" class="x-hidden-focus">Next</a>

但是,如果您按下下一步,我们可以看到现在有 2 个按钮:

<a href="getting-started" data-linktype="relative-path" class="x-hidden-focus">Previous</a>
<a href="adding-a-view" data-linktype="relative-path" class="x-hidden-focus">Next</a></p>

现在您的代码将是:

$(document).keypress(function(event){
    var which = (event.which ? event.which : event.keyCode);
    if(which == '13'){
        document.location = $("a.x-hidden-focus:contains('Next')").attr("href");
    }
});

编辑

我认为该类已经存在于元素上的假设是错误的。

由于仅在悬停链接后才添加该类,因此您需要仅根据文本查找链接:

$("a:contains('Next')");

但是,您可以通过使用容器类更精确:

$("div.step-by-step").find("a:contains('Next')").attr("href")

推荐阅读