2017-05-04 54 views
1

我想添加一個HTML到一個div,但將其呈現爲文本,而不是實際的HTML。我目前正在做的:JQuery:追加字符串作爲內容,而不是html

HTML

<div id="feed"></div> 

使用Javascript/JQuery的

$("#feed").append("<b>Hello World!</b>"); 

而且它呈現如下:

的Hello World

但我想普通的文本被渲染,這樣

<b>Hello World!</b> 

回答

2

轉義字符HTML [Ref]

function escapeHtml(unsafe) { 
 
    return unsafe 
 
    .replace(/&/g, "&amp;") 
 
    .replace(/</g, "&lt;") 
 
    .replace(/>/g, "&gt;") 
 
    .replace(/"/g, "&quot;") 
 
    .replace(/'/g, "&#039;"); 
 
} 
 

 
$("#feed").append(escapeHtml("<b>Hello World!</b>"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="feed"></div>

0

你檢查過

http://api.jquery.com/html/

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>html demo</title> 
    <style> 
    p { 
    margin: 8px; 
    font-size: 20px; 
    color: blue; 
    cursor: pointer; 
    } 
    b { 
    text-decoration: underline; 
    } 
    button { 
    cursor: pointer; 
    } 
    </style> 
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
</head> 
<body> 

<p> 
    <b>Click</b> to change the <span id="tag">html</span> 
</p> 
<p> 
    to a <span id="text">text</span> node. 
</p> 
<p> 
    This <button name="nada">button</button> does nothing. 
</p> 

<script> 
$("p").click(function() { 
    var htmlString = $(this).html(); 
    $(this).text(htmlString); 
}); 
</script> 

</body> 
</html> 
0

也許你可以這樣做:

$("#feed").append("&lt;b>Hello World!&lt;/b>"); 

或者:

$("#feed").append("<xmp><b>Hello World!</b></xmp>"); 

但請注意,xmp標記已被棄用。

3

使用text()代替append()這樣$("#feed").text("<b>Hello World!</b>");

如果您有更多的文字使用這樣

追加0

$("#feed").text("<b>Hello World!</b>"); 
 

 
//$("#feed").text($("#feed").text()+"<b>Hello World!</b>"); for more append text use like this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="feed"></div>

0

請您嘗試一下。

<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 

     $("#feed").text("<b>Hello World!</b>"); 
}); 
</script> 
</head> 
<body> 

<div id="feed"></div> 

</body> 
</html> 
0

爲此,您需要使用「.text」,它將簡單地附加文本,但不會呈現html標記。

$("#feed").text("<b>Hello World!</b>"); 

WorkingFiddleLink

相關問題