如何使用jQuery将输入元素更改为textarea

如何使用jQuery将输入元素更改为textarea

问题描述:

我有以下html:

<div>
    <input type="text" style="xxxx" size="40"/>
    <input type="text" style="xxxx" size="100"/>
    <input type="text" style="xxxx" size="100"/>
    <input type="text" style="xxxx" size="40"/>
</div>

现在,我想将大小为'100'的每个输入更改为与输入样式相同的文本区域.

Now I want to change each input whose size is '100' to a textarea which has the same style as the input.

我已经尝试过了:

$("input[size=100]").each(function(){
  //how to replace it?
});

有什么想法吗?

我使用了此处中找到的解决方案:

I used this solution found in the answers here:

$("input[size=100]").each(function() {
    var style = $(this).attr('style'), textbox = $(document.createElement('textarea')).attr({
        id : $(this).id,
        name : $(this).name,
        value : $(this).val(),
        style : $(this).attr("style"),
        "class" : $(this).attr("class"),
        rows : 6
    }).width($(this).width());
    $(this).replaceWith(textbox);
});

jQuery有一个.replaceWith()方法,可用于将一个元素替换为另一个元素.因此,请从输入中复制样式,并使用此方法,如下所示:

jQuery has a .replaceWith() method you can use to replace one element with another. So, copy your styles from the input and use this method, as follows:

$('input[size="100"]').each(function () {
    var style = $(this).attr('style'),
        textbox = $(document.createElement('textarea')).attr('style', style);
    $(this).replaceWith(textbox);
});

演示