我知道这个问题以前被问过,但在网上搜索后,似乎找不到一个直截了当的答案。
HTML代码:
<a id=myAnchor href=index.php>
jQuery(这两个都不起作用)
$('#myAnchor').click();
或者$('#myAnchor').trigger('click');
如何以最简单和高效的方式实现这个?
试一试:
$('#myAnchor')[0].click();
对我有效。
window.location = document.getElementById('myAnchor').href
点击只能触发点击事件/事件,而不能实际执行“跳转到链接-Href”操作。
您需要编写自己的处理程序,然后 $('#myAnchor').trigger('click'); 才能起作用...
$("#myAnchor").click(function(event)
{
var link = $(this);
var target = link.attr("target");
if($.trim(target).length > 0)
{
window.open(link.attr("href"), target);
}
else
{
window.location = link.attr("href");
}
event.preventDefault();
});
<a href="#" id="myAnchor">Click me</a>
<script type="text/javascript">
$(document).ready(function(){
$('#myAnchor').click(function(){
window.location.href = 'index.php';
});
})
</script>
onclick="window.location = this.href"
添加到您的 <a>
元素中。在此修改后,它可以按预期行为进行 .click()
。要对页面上的每个链接执行此操作,您可以添加以下内容:<script type="text/javascript">
$(function () {
$("a").attr("onclick", "window.location = this.href");
});
</script>
<button onclick="fun();">Magic button</button>
<!--The link you want to automatically click-->
<a href='http://www.ercafe.com' id="myAnchor">My website</a>
<script>
标签内部,<script>
function fun(){
actuateLink(document.getElementById('myAnchor'));
}
function actuateLink(link)
{
var allowDefaultAction = true;
if (link.click)
{
link.click();
return;
}
else if (document.createEvent)
{
var e = document.createEvent('MouseEvents');
e.initEvent(
'click' // event type
,true // can bubble?
,true // cancelable?
);
allowDefaultAction = link.dispatchEvent(e);
}
if (allowDefaultAction)
{
var f = document.createElement('form');
f.action = link.href;
document.body.appendChild(f);
f.submit();
}
}
</script>
复制并粘贴上述代码,点击“魔法按钮”
,您将被重定向到ErCafe.com
。
我遇到了类似的问题。尝试这个$('#myAnchor').get(0).click();
,这对我有用。
jQuery.trigger
http://api.jquery.com/trigger/来完成它。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
<a id="foo" onclick="action()"></a>
<script type="text/javascript">
function action(){
window.location.replace("https://dev59.com/Ymox5IYBdhLWcg3wnlpI")
}
$("#foo").trigger("click");
</script>
</body>
</html>
为了兼容性,请尝试这个;
<script type="text/javascript">
$(function() {
setTimeout(function() {
window.location.href = $('#myAnchor').attr("href");
}, 1500);
});
</script>
<a id="myAnchor" href="index.php">文本</a>
(带引号和适当的闭合标签)。 - Cᴏʀʏ