javascript 在“a href”元素上触发点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25097181/
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
Trigger click event on "a href" element
提问by user3429355
I am trying to click a href element on my html website. Problem is that click event is not triggered
我正在尝试单击我的 html 网站上的 href 元素。问题是点击事件没有触发
CODE:
代码:
HTML CODE:
HTML代码:
<div class="button" id="info" ></div>
<ul id="game-options">
<li><a href="#" id="SHOW_HELP" class="button help" title="Help">HELP</a></li>
</ul>
Function that clicks a href element:
单击 href 元素的函数:
$('#info').bind('click', function(e) {
alert ("button click triggered");
// This is what I tried so fat
//$('#SHOW_HELP').trigger('click');
//$('#SHOW_HELP').dispatchEvent(new Event('click'));
$('#SHOW_HELP').click();
});
回答by billyonecan
The click event is triggered, but you haven't bound a click handler so nothing will happen. If you want to simulate clicking the link you need to use the dom click method, ie. $('#SHOW_HELP')[0].click();
点击事件被触发,但你没有绑定点击处理程序所以什么都不会发生。如果要模拟单击链接,则需要使用 dom click 方法,即。$('#SHOW_HELP')[0].click();
回答by Borteo
It's actually working.
它实际上在起作用。
Here a JSFiddle example: http://jsfiddle.net/rZbk7/
这里有一个 JSFiddle 示例:http: //jsfiddle.net/rZbk7/
$('#info').on('click', function(e) {
alert("info triggered");
$('#show-help').click();
});
$('#show-help').on('click', function(e) {
alert("show-help triggered");
});
(not a big fun of snake case, I changed the name SHOW_HELP to show-help)
(蛇案没有太大的乐趣,我将名称 SHOW_HELP 更改为 show-help)
Click event is triggered. The problem is that you didn't define any action.
点击事件被触发。问题是您没有定义任何操作。
回答by imbondbaby
Alternatively, you can update the button's click event to change the window.location
in JavaScript.
或者,您可以更新按钮的单击事件以更改window.location
JavaScript。
Try this:
试试这个:
$(function(){
$('#info').click(function(){
window.location = $('#SHOW_HELP').attr('href');
});
});