插入文本区域
问题描述:
下面是HTML插入文本区域
<input type="text" id="textbox1" />
<input type="text" id="textbox2" />
<input type="text" id="textbox3" />
<input type="text" id="textbox4" />
<a href="#" id="change">Change</a>
<a href="#" id="change1">Change1</a>
我们下面的代码
var textbox = $("input[type='text']");
var textarea = $("<textarea id='textarea' rows='10' cols='35'></textarea>");
$("#change").click(function() {
$("input[type='text']").each(function(index) {
$(this).hide();
$(textarea).insertAfter(this);
});
});
$("#change1").click(function() {
$('textarea').remove();
$("input[type='text']").show();
});
答
你并不需要用户$()
选择了普通的HTML像<textarea id='textarea' rows='10' cols='35'></textarea>
和insertAfter
也是错误用法,在你的情况下最好使用.after
。这里有jsFiddle解决方案。
var textbox = $("input[type='text']");
var textarea = "<textarea id='textarea' rows='10' cols='35'></textarea>";
$("#change").click(function() {
$("input[type='text']").each(function(index) {
$(this).after(textarea);
$(this).hide();
});
});
$("#change1").click(function() {
$('textarea').remove();
$("input[type='text']").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="textbox" />
<input type="text" id="textbox" />
<input type="text" id="textbox" />
<input type="text" id="textbox" />
<a href="#" id="change">Change</a>
<a href="#" id="change1">Change1</a>
答
因为你没有在你的代码中使用textarea的ID,您可以将其删除
var textarea = $("<textarea rows='10' cols='35'></textarea>");
因为随着@guruprasadrao指出,ID必须是唯一的。
其次,当用户点击再次改变你可能不希望保留重新添加文字区域,因此将其更改为
$("#change").click(function() {
$("input[type='text']").each(function(index) {
if ($(this).next().attr("type") != "text")
{
$(this).next().remove();
}
$(textarea).insertAfter(this);
$(this).hide();
});
});
答
无需通过每个输入迭代。直接使用:
$("#change").click(function() {
$("input[type='text']").after($(textarea));
});
所以有什么问题? **在html中的任何元素的'id'必须是唯一的** –
希望你期待** ['this'](https://jsfiddle.net/Guruprasad_Rao/6u9vhp78/)** –