去除每个子元素的 html
strip html of each child element
假设我很脏 html 像这样...
let dirty = `
<pre>
pre tag with <b>html</b>
</pre>
<pre>
another pre tag with <b>html</b>
</pre>
`
我需要从 pre 标记的每个子项中删除 html...
我正在做这个...
let $ = cheerio.load(dirty)
$('pre').each(function() {
let text = $(this).text()
console.warn(text) // html are stripped
return `<pre>${text}</pre>`
});
console.log($.html()) // html are not stripped
我错过了什么..??
首先请注意,虽然从技术上讲您可以使用反引号分隔多行字符串,但 IE 完全不支持它,因此不能可靠地使用它。您需要使用引号 ('
) 或双引号 ("
)。
您的逻辑问题在于您在每个循环中定义了 text
变量,但不对其进行任何操作,因为从 each()
返回是多余的。
要解决此问题,您只需使用 text()
方法从给定元素中删除任何子元素 HTML。试试这个:
let dirty = '<pre>pre tag with <b>html</b></pre><pre>another pre tag with <b>html</b></pre>';
$('body').append(dirty);
$('pre').text(function(i, t) {
return t;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$('pre').each(function() {
let text = $(this).text()
// You need to inject cleaned string into the DOM
$(this).html(text)
});
console.log($('div').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<pre>
pre tag with <b>html</b>
</pre>
<pre>
another pre tag with <b>html</b>
</pre>
</div>
您需要实际分配新的 html,现在您没有将 html 设置为其他内容。以下将起作用
const cheerio = require("cheerio");
let dirty = `
<pre>
pre tag with <b>html</b>
</pre>
<pre>
another pre tag with <b>html</b>
</pre>
`;
let $ = cheerio.load(dirty);
$("pre").each(function() {
$(this).html($(this).text());
});
console.log($.html());
假设我很脏 html 像这样...
let dirty = `
<pre>
pre tag with <b>html</b>
</pre>
<pre>
another pre tag with <b>html</b>
</pre>
`
我需要从 pre 标记的每个子项中删除 html...
我正在做这个...
let $ = cheerio.load(dirty)
$('pre').each(function() {
let text = $(this).text()
console.warn(text) // html are stripped
return `<pre>${text}</pre>`
});
console.log($.html()) // html are not stripped
我错过了什么..??
首先请注意,虽然从技术上讲您可以使用反引号分隔多行字符串,但 IE 完全不支持它,因此不能可靠地使用它。您需要使用引号 ('
) 或双引号 ("
)。
您的逻辑问题在于您在每个循环中定义了 text
变量,但不对其进行任何操作,因为从 each()
返回是多余的。
要解决此问题,您只需使用 text()
方法从给定元素中删除任何子元素 HTML。试试这个:
let dirty = '<pre>pre tag with <b>html</b></pre><pre>another pre tag with <b>html</b></pre>';
$('body').append(dirty);
$('pre').text(function(i, t) {
return t;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$('pre').each(function() {
let text = $(this).text()
// You need to inject cleaned string into the DOM
$(this).html(text)
});
console.log($('div').html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<pre>
pre tag with <b>html</b>
</pre>
<pre>
another pre tag with <b>html</b>
</pre>
</div>
您需要实际分配新的 html,现在您没有将 html 设置为其他内容。以下将起作用
const cheerio = require("cheerio");
let dirty = `
<pre>
pre tag with <b>html</b>
</pre>
<pre>
another pre tag with <b>html</b>
</pre>
`;
let $ = cheerio.load(dirty);
$("pre").each(function() {
$(this).html($(this).text());
});
console.log($.html());