2016-01-22 80 views
0

下面是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(); 

}); 
+3

所以有什麼問題? **在html中的任何元素的'id'必須是唯一的** –

+0

希望你期待** ['this'](https://jsfiddle.net/Guruprasad_Rao/6u9vhp78/)** –

回答

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(); 
 

 
});
<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>

1

因爲你沒有在你的代碼中使用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(); 
    }); 
}); 
1

無需通過每個輸入迭代。直接使用:

$("#change").click(function() { 
    $("input[type='text']").after($(textarea)); 
});