javascript JQuery 点击链接不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12617901/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:40:41  来源:igfitidea点击:

JQuery click on link not working

javascriptjqueryhyperlinkclick

提问by 0x49D1

Ive the following code:

我有以下代码:

<script type="text/javascript">
$(document).ready(function(){
    shortcut.add("Ctrl+Alt+N", function() {
        $("#btnSave").click();
    });
});
</script>

where btnSave is anchor element with ID btnSave, shortcut is from http://www.openjs.com/scripts/events/keyboard_shortcuts/. If i change the line $("#btnSave").click();to document.getElementById("btnSave").click()- all works fine. The question is why jquery implementation is not working in my case?
PS: made jsfiddle for my case: http://jsfiddle.net/0x49D1/WCmeU/
Here is the guy with similar problem: http://forums.asp.net/t/1591818.aspx

其中 btnSave 是 ID 为 btnSave 的锚元素,快捷方式来自http://www.openjs.com/scripts/events/keyboard_shortcuts/。如果我将线路更改$("#btnSave").click();document.getElementById("btnSave").click()- 一切正常。问题是为什么 jquery 实现在我的情况下不起作用?
PS:为我的案例制作了 jsfiddle:http: //jsfiddle.net/0x49D1/WCmeU/
这是有类似问题的人:http ://forums.asp.net/t/1591818.aspx

回答by Nelson

Instead of $("#btnSave").click();try with $("#btnSave").trigger('click');

而不是$("#btnSave").click();尝试$("#btnSave").trigger('click');

You can also use $("#btnSave")[0].click();which is jquery equivalent to document.getElementById("btnSave").click();

您还可以使用$("#btnSave")[0].click();哪个 jquery 等效于document.getElementById("btnSave").click();

Update:
It's not possible to simulate a user link click from javascript, for security reasons, all you can do is attach your own handler for clickevent and redirect based on the hrefof the link, like so:

更新
无法从 javascript 模拟用户链接点击,出于安全原因,您所能做的就是附加您自己的click事件处理程序并基于href链接的重定向,如下所示:

$("#btnSave").bind('click', function() {
    window.location.href = $(this).attr('href');
});

回答by soonji

try this

试试这个

<script type="text/javascript"> 
      $(document).ready(function(){
         shortcut.add("Ctrl+Alt+N", function() {
            $("#btnSave").live('click',function(){
           // do stuff here
            });
         }); 
      }); </script>
<script type="text/javascript"> 
      $(document).ready(function(){
         shortcut.add("Ctrl+Alt+N", function() {
            $("#btnSave").live('click',function(){
           // do stuff here
            });
         }); 
      }); </script>