【问题标题】:Change /n to <br /> in text from textarea在 textarea 的文本中将 /n 更改为 <br />
【发布时间】:2013-06-14 09:51:05
【问题描述】:

在 dblclick 上 - DIV 被替换为 TEXTAREA。您可以编辑文本。

模糊时 - TEXTAREA 被替换为 DIV。新行替换为“br />”。

第一个问题 - 在已编辑的文本中 - “br />” 不像文本中的换行或换行,而是像文本“ br />”。如何解决?

第二个问题 - 示例中有一个“br />”。当您第一次编辑示例中的文本时,此“br />”不会更改为换行符,而只会更改为简单的空格(&nsbp;)。为什么第一次尝试编辑原始文本时会出现此错误?

jsFiddle DEMO

HTML

<div id="meText">Click to edit <br /> this text.</div>

jQuery

$(function(){
    $("#meText").live('click',function(){
        var originalDiv = this;
        $(this).replaceWith($("<textarea></textarea>").text($(this).text().replace(/<br\s?\/?>/g,"\n")).width($(this).width()).height($(this).height()).blur(function(){$(this).replaceWith($(originalDiv).text($(this).val().replace(/\r\n|\r|\n/g,"<br />")));}));
    });
});

【问题讨论】:

  • @Partik 是我的 ans 为你工作..??

标签: jquery textarea newline break


【解决方案1】:

尝试使用 .html() 而不是 .text() 并更改 replace 之类的

$(function(){
$("#meText").on('click',function(){
    var originalDiv = this;
    $(this).replaceWith($("<textarea></textarea>").html($(this).text().replace(/\n/g, "<br />")));
  });
});

查看此LINK。您可以将宽度和高度添加到此

【讨论】:

  • 谢谢,您对 text()html() 的看法是正确的,但您的示例不起作用。当我 dbclik 进行编辑时 - 仍然存在相同的错误。
【解决方案2】:

请使用下面的代码

  $(this).replaceWith($("<textarea></textarea>").text($(this).html().replace(/<br\s?\/?>/g,"\n")).width($(this).width()).height($(this).height()).blur(function(){$(this).replaceWith($(originalDiv).html($(this).val().replace(/\r\n|\r|\n/g,"<br />")));}));

您正在使用某些地方 text() 而不是 html()。如果我们使用 text() 它会消除 html 标签

【讨论】:

    猜你喜欢
    • 2021-10-10
    • 2014-04-08
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 2011-12-05
    • 2011-01-18
    • 2013-08-19
    • 1970-01-01
    相关资源
    最近更新 更多