下面是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();
});
答案 0 :(得分:1)
您不需要为$()
这样的普通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();
});
&#13;
<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>
&#13;
答案 1 :(得分:1)
因为您没有在代码中使用textarea id,所以可以将其删除
var textarea = $("<textarea rows='10' cols='35'></textarea>");
因为@guruprasadrao指出,id必须是唯一的。
其次,当用户再次点击更改时,您可能不希望再次添加textareas,因此将其更改为
$("#change").click(function () {
$("input[type='text']").each(function( index ) {
if ( $(this).next().attr( "type" ) != "text" )
{
$(this).next().remove();
}
$(textarea).insertAfter(this);
$(this).hide();
});
});
答案 2 :(得分:1)
无需遍历每个输入。直接使用:
$("#change").click(function () {
$("input[type='text']").after($(textarea));
});