我有这样的div
<div id="asdf">
<div>
<p>ASDF IS AWESOME</p>
</div>
<h1>Just another Headline</h1>
<nav>
<ul>
<li class="listitem">Hey</li>
</ul>
</nav>
</div>
并需要一个jQuery
或vanilla JavaScript
函数,将整个内容转换为此
<div id="asdf"
<div>
<p>ASDF IS AWESOME</p>
</div>
<h1>Just another Headline</h1>
<nav>
<ul>
<li class="listitem"Hey</li>
</ul>
</nav>
</div>
所以我只想逃避<
和>
我尝试了.replace
和.text()
答案 0 :(得分:3)
试试
var html = $('#asdf').html();
var escaped=$('<div/>').text(html).html();
console.log(escaped);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="asdf">
<div>
<p>ASDF IS AWESOME</p>
</div>
<h1>Just another Headline</h1>
<nav>
<ul>
<li class="listitem">Hey</li>
</ul>
</nav>
</div>
&#13;
答案 1 :(得分:0)
试试这个:只使用1个功能,然后就可以在任何地方使用
$(document).ready(function(){
$selector = $('#asdf');
console.log(htmlEntities($selector));
function htmlEntities(str) {
str = str.html();
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="asdf">
<div>
<p>ASDF IS AWESOME</p>
</div>
<h1>Just another Headline</h1>
<nav>
<ul>
<li class="listitem">Hey</li>
</ul>
</nav>
</div>
您可以参考:https://css-tricks.com/snippets/javascript/htmlentities-for-javascript/