br 标签在使用 JQUERY 文本函数将内容从文本区域替换到 DIV 时不起作用

br tag is not working while replace the content from textarea to DIV using JQUERY text function

本文关键字:文本 区域 替换 不起作用 DIV 标签 JQUERY br 函数      更新时间:2023-09-26

br 标签在 DIV 上不起作用。我收到来自"更新内容:textarea"字段的消息。该消息有 2 行,如"拉玛"下一行"林加姆"。但结果是$("#editQuotesRowLabel_Q_013").text(replaceContent);的"拉玛
林加姆"

如何在DIV中创建新行?

这是我的代码:

function updateQuotes(){    
    var weg_quotes = $("#weg_quotes_Q_013").val();  
    replaceContent = weg_quotes.replace("'n", "<br>", "g");         
    $("#editQuotesRowLabel_Q_013").text(replaceContent);
}
Update Content: <textarea placeholder="Update your content..." id="weg_quotes_Q_013" name="weg_quotes" cols="80" rows="3" class="appQuotesTextarea" maxlength="200" required=""></textarea>
<button onclick="updateQuotes()" id="Q_013" name="update-btn" class="appQuotesBtn">Update</button>
<div id="editQuotesRowLabel_Q_013" class="appQuotesLabel">
    This is content div. 
</div>

要使用 jquery 插入 HTML 内容,您需要使用 .html() 而不是 .text() 。所以在你的情况下,你最终会得到:

 $("#editQuotesRowLabel_Q_013").html(replaceContent);
 //                              |_ use html() instead of text()

源:

  • .html()
  • .text()

只需使用 .html() 而不是 .text(),因为 textarea 内容也将包含
标签,.html()也可以显示 html,.text()只会考虑文本 - 它不会在div 中设置 html 标签(
此处标记),因此请使用 .html() 而不是.text()

function updateQuotes(obj){ 
    var weg_quotes = $("#weg_quotes_Q_013").val();  
    replaceContent = weg_quotes.replace("'n", "<br>", "g");   
    $("#editQuotesRowLabel_Q_013").html(replaceContent);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Update Content: <textarea placeholder="Update your content..." id="weg_quotes_Q_013" name="weg_quotes" cols="80" rows="3" class="appQuotesTextarea" maxlength="200" required=""></textarea>
<button onclick="updateQuotes(this)" id="Q_013" name="update-btn" class="appQuotesBtn">Update</button>
<div id="editQuotesRowLabel_Q_013" class="appQuotesLabel">
    This is content div. 
</div>

试试这个:

$("#editQuotesRowLabel_Q_013").html(replaceContent);

尝试使用html()而不是text()

这将允许您使用 html 标记:)

我不确定那个 replace() 方法是什么,但它替换的是

str.replace(pattern/string, function/replacement)

所以你的代码应该是

replaceContent = weg_quotes.replace(/'n/g, "<br>");  

当您将 HTML 插入div 时,您应该使用.html()

$("#editQuotesRowLabel_Q_013").html(replaceContent);

试试这个.html()而不是.text()

$("#editQuotesRowLabel_Q_013").html(replaceContent);