【问题标题】:how to change an input element to textarea using jquery [duplicate]如何使用jquery将输入元素更改为textarea [重复]
【发布时间】:2013-06-13 09:08:37
【问题描述】:

我有以下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”的输入更改为与输入具有相同样式的文本区域。

我试过这个:

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

有什么想法吗?


我使用了答案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);
});

【问题讨论】:

  • 这对 Google 来说是微不足道的。
  • 我试过了,还是不行。顺便说一句,我认为我的帖子不值得投反对票。
  • 谷歌不工作?它对我有用。我得到的第一个打击是例如jQuery change hidden input type to textarea - 如果您对 that 有特定问题,您应该将它们添加到问题中
  • google.com.hk/… 。这就是我得到的。
  • 另外,我发现这个$('code').contents().unwrap().wrap('&lt;pre/&gt;'); 但它不适用于输入元素。

标签: jquery


【解决方案1】:

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

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

Demo

【讨论】:

    【解决方案2】:

    尝试一些类似的东西

    $('input[size="100"]').each(function()
    {
        var textarea = $(document.createElement('textarea'));
        textarea.text($(this).val());
    
        $(this).after(textarea).remove();
    });
    

    这是一个例子: http://jsfiddle.net/SSwhK/

    【讨论】:

      【解决方案3】:

      这样试试

      $("input").each(function(){
            if($(this).attr('size') == "100") {
                   my_style = $(this).attr('style');
                   $(this).replaceWith("<textarea style='"+my_style+"'></textarea>");
            }
      });
      

      【讨论】:

      • 你误会了,我就是不知道怎么换。
      • 查看我的编辑......我的回答也不值得像你的问题那样投反对票
      • 我同意这不值得一票否决...但是为什么要首先回答这样一个懒惰的问题,让用户可以提出越来越多的问题呢?只是说。
      • 是的@Pekka웃,但我认为这很简单让他澄清
      【解决方案4】:
      $(document).ready(function(){
          $("input[size=100]").each(function(){
            //how to replace it?
              $(this).after('<textarea style="xxxx"></textarea>').remove();
          });
      });
      

      查看http://jsfiddle.net/6JH6B/

      【讨论】:

        猜你喜欢
        • 2021-10-04
        • 2012-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-15
        • 2015-11-27
        • 1970-01-01
        相关资源
        最近更新 更多