javascript - 如何在 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 中的用户脚本(希望这会有所帮助)。
解决方案
您可以尝试简单地导航到您尝试单击的链接所描述的 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")
推荐阅读
- javascript - 光标 - 动画 javascript
- c# - 如何将 d 的索引返回到其错误消息
- angular - 如何在函数 gleich 中使用变量 rechenoperator2?
- javascript - 如果数组包含重复项,则将两个值合并为一个
- entity-framework-core - 使用 GROUP BY 检索组中的最新行
- google-bigquery - 来自以太坊的 BigQuery 数据中可用的指标
- javascript - 错误时的javascript axios控制台日志响应
- java - 没有可用的“com.milkdairy.dao.userRepository”类型的合格 bean:预计至少有 1 个有资格作为自动装配候选者的 bean
- macros - 从 Enter 确认 Atom 解除绑定更正
- python - 为什么 Python XLSWRITER 单元格公式不能以编程方式工作?