多个,在光标处插入所需文字,求解决办法

belin520 2012-02-26 02:26:06
<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
...全文
285 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
孟子E章 2012-02-26
  • 打赏
  • 举报
回复
你可以这样
<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>
huaye 2012-02-26
  • 打赏
  • 举报
回复
没明白你说的啥意思。
p2227 2012-02-26
  • 打赏
  • 举报
回复
那只是一个举例,我都不知道你想在哪里触发这个填充的事件
belin520 2012-02-26
  • 打赏
  • 举报
回复
onclick不在<input id=d1 type=text >,即多个type=text ,只有唯一的 type=button

[Quote=引用 1 楼 p2227 的回复:]
HTML code

<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//documen……
[/Quote]
p2227 2012-02-26
  • 打赏
  • 举报
回复
<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>

87,921

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧