【问题标题】:html <a> activate on click on enter pressedhtml <a> 在点击输入时激活
【发布时间】:2014-06-17 07:35:15
【问题描述】:

我希望在按下回车按钮时激活链接 &lt;a href='#' onclick='function()'&gt; 的 onclick 事件。这应该可以工作,但我似乎无法正常工作。 Trigger a button click with JavaScript on the Enter key in a text box 。这也不适用于按钮。

原因可能是因为加载问题,我使用 ajax 运行和加载大部分界面,某些计算需要相当长的时间,所以我想我应该使用 ajax 来显示我的页面元素,这样我就可以更新真实的时间而不是让用户等待服务器 5 到 10 秒。然而,这似乎使下面的代码不起作用。

我的代码

//This comes from a different php file which is read out on the server with
//readfile() in php after an ajax call. In other words it echoes the 
//contents of this file on the page including this link. 
echo "<a href='#' onclick='dosomething()' ID='Enter'>Click me</a>";

//js
$("#Enter").keyup(function(event){
    if(event.keyCode == 13){
        $("#Enter").click();
    }
});

function dosomething(){
    //activate some code depends on the link.
}

那么我该如何让它发挥作用。在通过ajax导入的链接上激活oncl​​ick on enter?这甚至可能吗?

【问题讨论】:

    标签: javascript php jquery html ajax


    【解决方案1】:

    Working Demo

    试试这个,

    使用keypress 事件,它不会在#Enter 上触发,因为它是&lt;a&gt; 标记。

    $(document).keypress(function(event){
    
        if(event.keyCode == 13){
            $("#Enter").click();   //OR $("#Enter").trigger('click');
        }
    });
    
    function dosomething(){
        alert('..');
        //activate some code depends on the link.
    }
    

    【讨论】:

      【解决方案2】:

      你可以这样做

      $("#Enter").keypress(function(event){
          if(event.keyCode == 13){
             dosomething();
          }
      });
      

      你也可以Trigger点赞

      $("#Enter").trigger('click');
      

      【讨论】:

      • 那太好了,但是我希望这个功能可以在应用程序中具有输入 ID 的所有链接上运行,并且不会同时显示这些链接。另外在某些情况下,它需要用户输入。就像登录()一样。所以这会完全破坏它,导致一些随机错误消息在您的页面上弹出,因为按下了输入。
      • 那么你必须使用类选择器而不是 ID,因为根据 DOM 规则你必须将 ID 设置为唯一
      • 你能告诉我怎么做吗,我对php很熟悉,但对jquery不太熟悉
      猜你喜欢
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多