如何从 javascript 或 jquery 单击锚标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30565512/
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 click an anchor tag from javascript or jquery
提问by 151291
Have an anchor tag, trying to click it from the javascript but not responding, while loading the page it should go to next.php
without click anchor tag manually.how can I archive this?
有一个锚标记,试图从 javascript 中单击它但没有响应,在加载页面时它应该去next.php
而不手动单击锚标记。我该如何存档?
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jquery-2.0.3.js"></script>
<script type="text/javascript">
alert("hai");
$(document).ready(function() { $('#about').click(); });
</script>
</head>
<body>
<div>
<a href="next.php" id="about">click here</a>
</div>
</body>
</html>
回答by Shaunak D
Use $('selector')[0]
, as $('selector')
returns a jQuery object, so $('selector').click()
will fire the click handler, while $('selector')[0].click()
would fire the actual click.
使用$('selector')[0]
, as$('selector')
返回一个 jQuery 对象,因此$('selector').click()
将触发点击处理程序,而$('selector')[0].click()
将触发实际点击。
$(document).ready(function () {
$('#about')[0].click(); //$('#about').get(0).click();
});
回答by PhuLuong
You can not use javascript to fire click event
您不能使用 javascript 来触发点击事件
It should use
它应该使用
<script type="text/javascript">
$(document).ready(function() {
document.location.href='/next.php'
});
</script>
回答by Alex
Here is the code that can help you
这是可以帮助您的代码
$(document).ready(function() {
$(document).ready(function() {
$('a').trigger('click');
});
})
function abc() {
alert("");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="abc()">click me not</a>
If you want the recommended way then use this inside $(document).ready
如果你想要推荐的方式,那么在 $(document).ready 中使用它
window.location="where ever you want to go";
回答by Kurenai Kunai
If you want the page to go to next.php
without clicking then place the window.location
directly into $(document).ready(function() { });
如果您希望页面next.php
无需点击window.location
即可直接进入$(document).ready(function() { });
Click()
function is used when you want to trigger click event. ie. when you want to trigger some action when anchor tag is clicked.
Click()
函数用于触发点击事件。IE。当您想在单击锚标记时触发某些操作时。
<script>
alert("hai");
$(document).ready(function() {
window.location = 'next.php'; //If you wish the page to automatically go to next page on page load.
$('#about').click( // If you wish to do something clicking anchor
function(){
alert("Hello");
});
});
</script>
回答by ndlinh
$(document).ready(function() { $('#about').trigger('click'); });
Updated:
更新:
$(document).ready(function() { $('#about')[0].click(); });