我知道之前曾有人问过这个问题,但是在网上搜索后,我似乎找不到直接的答案。
HTML
<a id=myAnchor href=index.php>
jQuery(这两个都不起作用)
$('#myAnchor').click();
或
$('#myAnchor').trigger('click');
最简单,最有效的方法是什么?
尝试一下:
$('#myAnchor')[0].click();
它对我有用。
window.location = document.getElementById('myAnchor').href
单击只是触发单击事件,而不是实际的“ goto-the-links-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>
复制粘贴上面的代码,然后单击'Magic button'
按钮,您将被重定向到ErCafe.com
。
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("http://stackoverflow.com/q/9081426/5526354")
}
$("#foo").trigger("click");
</script>
</body>
</html>
$('#myAnchor').get(0).click();
这对我有用