Javascript 检查是否选择了具有特定类型的输入

Javascript 检查是否选择了具有特定类型的输入,javascript,Javascript,我正在使用下面的代码检查输入字段是否被选中,但我不知道问题出在哪里,因为它不起作用 <html> <head> <title>Test </title> <head> <body> <form > <input type="text" id="select" value="select"/> </form> <script type="text/javascript" &g

我正在使用下面的代码检查输入字段是否被选中,但我不知道问题出在哪里,因为它不起作用

   <html>
<head>
<title>Test  </title>
<head>
<body>
<form >
<input type="text" id="select" value="select"/>
</form>

<script type="text/javascript" >
var d, len,i, j, el;
d=document.forms;
len=d.length;
for(i=0; i<len; i++){
el=d[i].elements;
 for(j=0;j<el.length; j++)
  if(el[j].type == "text" && el[j].focus())
  {
  alert("you selected an input field with type text");
  }
}
</script>
</body>
</html>

测验
变量d,len,i,j,el;
d=文件格式;
len=d.长度;

对于(i=0;i我采用代码的以下部分:

df=document.forms;
len=d.length;
for(i=0; i<len; i++)
els=d[i].elements;
因此,您将元素放入一个名为
els
的变量中;然后,您尝试从一个名为
el
的变量中读取


基本上:在读取变量之前,应该确保它包含一些内容;-)

而且,为了帮助您,您应该安装一个调试扩展,如Firefox的Firebug(或使用Chrome提供的控制台):它通常会给出有趣的错误消息,如下所示:


(来源:)



在OP编辑问题后进行编辑

我想说,下一步是在需要的地方添加
{}

如果不将
{}
放在
for()
之后,则循环中将只执行一条指令。
简言之,如果您有:

for (i=0 ; i<10 ; i++)
    console.log('hello');
    console.log('world');
所以,即使你没有语法错误,现在,你的代码可能不会像你想象的那样循环



最后,如果您想找出哪个元素具有焦点,您应该查看属性(引用):

返回当前关注的元素,即将 如果用户键入任何击键事件,则获取击键事件


它似乎还不是很标准,因为它是HTML-5规范的一部分,但似乎有几种浏览器支持它:

最初作为专有的DOM扩展引入Internet 在Explorer 4中,Opera和Safari也支持此属性(自 第4版)


如果需要使用事件处理程序,此脚本将在加载后立即运行

window.onload=function(){
  var els=document.getElementsByTagName('input');
  //Gets all the input elements
  for(var i=0;i<els.length;i++){
    //Attach an event handler that gets called when the element has focus
    els[i].onfocus=checkElem;
  }
  //for your example you could do this all in one line since you only have one element.
  //document.getElementById('select').onfocus=checkElem;
}

var checkElem(){
  //Check to see if the input element that registered the event is text or not
  if(this.type=='text'){
    alert('You have selected a text input');
  }
  else{
    alert('You have selected a non-text input');
  }
}
window.onload=function(){
var els=document.getElementsByTagName('input');
//获取所有输入元素
对于(var i=0;i
for (i=0 ; i<10 ; i++) {
    console.log('hello');
    console.log('world');
}
window.onload=function(){
  var els=document.getElementsByTagName('input');
  //Gets all the input elements
  for(var i=0;i<els.length;i++){
    //Attach an event handler that gets called when the element has focus
    els[i].onfocus=checkElem;
  }
  //for your example you could do this all in one line since you only have one element.
  //document.getElementById('select').onfocus=checkElem;
}

var checkElem(){
  //Check to see if the input element that registered the event is text or not
  if(this.type=='text'){
    alert('You have selected a text input');
  }
  else{
    alert('You have selected a non-text input');
  }
}