【问题标题】:attempting to make enter button 'clickable'试图使输入按钮“可点击”
【发布时间】:2013-06-13 14:11:11
【问题描述】:

我想让一个“搜索”按钮在点击回车时可以点击。

这是我的html

<input type="text" runat="server" id="txtSearch" onkeypress="searchKeyPress(event);" 
<input type="button" runat="server" style="padding:5px;" id="butSearch" onserverclick="butSearch_Click" value="Search" disabled/>

这是我正在使用的 javascript

function searchKeyPress(e) { 
  if (typeof e == 'undefined' && window.event) { e = window.event; }
  if (e.keyCode == 13) {
    document.getElementById("butSearch").click();
  }
}

但是我得到一个错误

'Uncuaght TypeError:Cannot call method click of nul'

可能会就我为什么会收到此错误提供建议,是否有更好的替代方法来实现此错误?

【问题讨论】:

  • 使用.onclick() 而不是.click()

标签: javascript asp.net javascript-events


【解决方案1】:

那些runat="server" 是必需的吗?您会收到错误消息,因为当searchKeyPress 被调用时,您的按钮不存在(还)。要么它在 DOMContentLoaded 之前被触发,要么 asp.net 正在用你的按钮做一些时髦的事情,将它完全排除在 DOM 之外。

还有一些通用的 JavaScript 提示:

function searchKeyPress(e) { 
  // a much cleaner "use var, or assign if not defined":
  e = e || window.event;

  // strict comparison:
  if (e.keyCode === 13) {

    // verify we have a button:
    var btn = document.getElementById("butSearch");

    if (btn) {
      btn.click();
    } else {
      // btn does not exist. arbitrary code goes here
    }
  }
}

【讨论】:

    【解决方案2】:

    尝试在输入标签内输入=“提交”。

    【讨论】:

      【解决方案3】:

      你可以这样做:

      function searchKeyPress(e) { 
          e = e || window.event;
          var key = e.keyCode || e.which;
          if (key == 13) {
              document.getElementById("butSearch").click();
          }
      }
      

      【讨论】:

        【解决方案4】:

        在 ASP.NET 中,客户端生成的 id 不是您在 ASP.NET 标记中看到的那些(查看生成的源代码) 您需要调用控件的 ClientID 属性才能通过 javascript 或 jQuery 访问它。

        你可以试试:

        function searchKeyPress(e) { 
          if (typeof e == 'undefined' && window.event) { e = window.event; }
          if (e.keyCode == 13) {
            document.getElementById('<%=butSearch.ClientID%>').click();
          }
        }
        

        如果您了解 ASP.NET Id 的生成方式,您还可以使用控件的ClientIDMode,将其设置为静态。

        【讨论】:

          猜你喜欢
          • 2012-10-18
          • 1970-01-01
          • 1970-01-01
          • 2017-06-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-08
          • 2013-12-13
          相关资源
          最近更新 更多