jQuery 如何模拟锚链接点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4338161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to simulate anchor link click
提问by RayLoveless
I'm trying to trigger a link click for .jquery. Does someone know why the following doesn't work.
我正在尝试触发 .jquery 的链接点击。有人知道为什么以下不起作用。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>test</title>
</head>
<body>
<div>
<a id="google_link" href="http://google.com" target="_blank">click to go to google</a>
</div>
<div id="google_link_proxy">click here to do the same as the link above</div>
<script type="text/javascript">
$("#google_link_proxy").click(function(event){
$("#google_link").click();
});
</script>
</body>
</html>
采纳答案by Jeff the Bear
Looks like your $("google_link_proxy")
selector is off. Try $("#google_link_proxy")
.
看起来您的$("google_link_proxy")
选择器已关闭。试试$("#google_link_proxy")
。
You also need to close the observe call with })
.
您还需要使用 关闭observe 调用})
。
Those are the syntax errors with the code above though I don't think those functions are provided in jQuery by default.
这些是上面代码的语法错误,尽管我认为默认情况下 jQuery 中没有提供这些功能。
Here is what I think you're after:
这是我认为你所追求的:
$("#google_link_proxy").click(function(event){
window.open($("#google_link").attr('href'),'_blank')
});
回答by Roman Starkov
The jQuery method completely ignores href
:
jQuery 方法完全忽略href
:
$('#google_link').click(); // ignores href!
The native DOM method does the right thing:
本机 DOM 方法做正确的事情:
$('#google_link')[0].click();
This works regardless of whether the href
is a URL, a fragment (e.g. #blah
) or even a javascript:
.
无论href
是 URL、片段(例如#blah
)还是javascript:
.
回答by Wandering Zombie
If you use jQuery and the native DOM, the anchor can be clicked
如果使用 jQuery 和原生 DOM,则可以单击锚点
// insert an <a> into document and click it **natively**
// (.get(0) returns the DOM element)
$('<a id="fred99" />').attr('href', '#david').attr('target', '_blank')
.text('LINK').appendTo('body').get(0).click();
// now we've clicked, tidy up
$('#fred99').remove();
回答by epascarello
回答by pixelbobby
Make sure you have your jQuery code wrapped in a readyblock like so
确保你的 jQuery 代码像这样包装在一个准备好的块中
$(document).ready(function(){/* your code here */});
This ensures scripts are fired afterall the content and images are loaded.
这可确保在加载所有内容和图像后触发脚本。
回答by Vasfed
This can be done without jQuery:
这可以在没有 jQuery 的情况下完成:
document.querySelector('#google_link').click()