日期:2014-05-16  浏览次数:20454 次

多个<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>