【问题标题】:shouldn't keep textarea data?不应该保留 textarea 数据?
【发布时间】:2011-10-09 11:55:58
【问题描述】:

我在 form 中有一个 textarea

<form action="#" id="container">
  <textarea id="txt" cols="100" rows="5">Good bye</textarea>
</form>

我只想用 div 替换这个 form

$("#container").replaceWith(function() {
    return "<div>" + $(this).html() + "</div>";
});

这没有任何问题,但如果我之前使用 replaceWith 方法更改 textarea 值:

$("#txt").val("hello world");

最终的内容是 div 内的 textarea,带有“再见”文本,而不是预期的“hello world”。你有一个demo here

为什么会这样?如何将 form 替换为 div 保留 textarea 内容?

【问题讨论】:

    标签: jquery textarea


    【解决方案1】:

    .val() 正在更改 textarea 的值(表示提交表单时发送的数据),不一定是其内部文本/HTML.. 这样做请改用.html()

    $("#txt").html("hello world"); 
    

    Updated jsFiddle.

    【讨论】:

      【解决方案2】:

      This works:

      $("#txt").val("hello world");
      $("#container").replaceWith(function() {
          return $('<div />').append($(this).contents());
      });
      

      问题在于使用.html() 序列化html。在 DOM 节点方面工作要好得多。这也将保留事件处理程序。


      这是另一种方式:

      $('#container').wrapInner('<div/>').children().unwrap();
      

      【讨论】:

        【解决方案3】:

        试试这个,(改用.html())(html() 将值插入到 textarea 中,.val() 没有)

        http://jsfiddle.net/kRGqR/5/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-26
          • 2013-01-29
          • 1970-01-01
          相关资源
          最近更新 更多