首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

多个<input type=text>在光标处插入所需文字,求解决方法

2012-03-09 
多个input typetext,在光标处插入所需文字,求解决办法input id1 typetext /input id2 typetext

多个<input type=text>,在光标处插入所需文字,求解决办法
<input id=1 type=text /> 

<input id=2 type=text />
.
.
.
.
请问如何在光标处插入文字,或者在指定input插入文字,附一简单的在唯一input插入文字的JS,求修改

function test(str){ //在光标处插入内容

  var tc = document.getElementById("text");
  var tclen = tc.value.length;
  tc.focus();
  if(typeof document.selection != "undefined")
  {
  document.selection.createRange().text = str;  
  }
  else
  {
  tc.value = tc.value.substr(0,tc.selectionStart)+str+tc.value.substring(tc.selectionStart,tclen);
  }
}

但是从第一行可以知道他只能指定唯一ID


[解决办法]
你可以这样

HTML code
<script type="text/javascript">    var lastInput = null;    window.onload = function () {      inputs = document.getElementsByTagName("input");      for (i = 0; i < inputs.length; i++) {        if (inputs[i].type.toLowerCase() == "text") {          inputs[i].onfocus = function () {            lastInput = this;          }        }      }    }    function AddContent(str) {      if (lastInput) {        lastInput.focus();      }      if (typeof document.selection != "undefined") {        document.selection.createRange().text = str;      }      else {        lastInput.value = lastInput.value.substr(0, lastInput.selectionStart) + str + lastInput.value.substring(lastInput.selectionStart, lastInput.value.length);      }    }  </script></head><body>  <form>  <input id="Text1" type="text" />  <input id="Text2" type="text" />  <input id="Text3" type="text" />  <input id="Text4" type="text" />  <input id="Text5" type="text" />  <input id="Text6" type="text" />  <input type="button" onclick="AddContent('新内容')" value="插入" />  </form></body></html> 

热点排行