<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

解决方案 »

  1.   

    <input id=d1 type=text onclick="test('123',this)" />  <input id=d2 type=text onclick="test('123',this)" />
    <script>
    function test(str,obj){ //在光标处插入内容  var tc = obj//document.getElementById(id);
      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);
      }
    }
    </script>
      

  2.   

    onclick不在<input id=d1 type=text >,即多个type=text ,只有唯一的 type=button
      

  3.   

    你可以这样
    <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>