企图让回车键“可点击” [英] attempting to make enter button 'clickable'

查看:121
本文介绍了企图让回车键“可点击”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在点击进入做一个​​搜索按钮,可点击

I want to make a 'search' button clickable upon clicking enter.

这是我的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

This is the javascript I am using

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

不过,我得到一个错误

I am however getting an error

'Uncuaght TypeError:Cannot call method click of nul'

也许是为什么我得到这个错误,是有在实现这一目标的更好的选择的建议?

Advice perhaps on why I get this error and is there a better alternative at achieving this?

推荐答案

是那些 =服务器要求?你的错误,因为当 searchKey preSS 被调用,你的按钮不存在(还)。无论它被DOMContentLoaded之前触发,或asp.net正在做的事情时髦与你的按钮,保持了DOM完全。

are those runat="server" required? you get the error because when searchKeyPress gets called, your button doesn't exist (yet). Either it's being triggered before DOMContentLoaded, or asp.net is doing funky things with your button, keeping it out of the DOM entirely.

也有一些普遍的JavaScript提示:

Also some general JavaScript tips:

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
    }
  }
}

这篇关于企图让回车键“可点击”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆