使用cheerio替换属性值 [英] Replace the attribute value using cheerio
本文介绍了使用cheerio替换属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码用于替换所有< img>
标记 src
的值。但是以下代码不会修改原始文档。 $。html
打印原始文档,而不打印修改后的文档。
The following code is used to replace all the <img>
tags src
value. But the following code does not modify the original document. $.html
prints the original document and not the modified one.
$ = cheerio.load(data);
$("img").each(function() {
var old_src=$(this).attr("src");
var new_src = "/my_cached_image?url=" + encodeURIComponent(old_src);
$(this).prop("src", new_src);
});
modified_data = $.html();
推荐答案
您有一个非常小的错误,
You have a very small error, "src" in an img it's an attribute and not a property.
因此此代码将起作用:
var cheerio = require("cheerio");
var data = "<img src='yahoo.com'/>"
$ = cheerio.load(data);
$("img").each(function() {
var old_src=$(this).attr("src");
var new_src = "/my_cached_image?url=" + encodeURIComponent(old_src);
console.log(new_src);
$(this).attr("src", new_src);
});
console.log($.html());
输出为
<img src="/my_cached_image?url=yahoo.com">
这篇关于使用cheerio替换属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文