【问题标题】:Replace the attribute value using cheerio使用cheerio替换属性值
【发布时间】:2016-03-15 12:53:44
【问题描述】:

以下代码用于替换所有<img>标签src值。但是下面的代码并没有修改原始文件。 $.html 打印原始文档而不是修改后的文档。

    $ = 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();

【问题讨论】:

    标签: javascript node.js cheerio


    【解决方案1】:

    你有一个很小的错误, img 中的“src”是一个属性,而不是一个属性。

    所以这段代码可以工作:

    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">
    

    【讨论】:

      【解决方案2】:

      使用.attr('src', new_src) 而不是.prop()。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-01
        • 1970-01-01
        • 2012-11-15
        • 2019-03-11
        • 2019-09-23
        • 2014-12-16
        • 2020-09-14
        • 1970-01-01
        相关资源
        最近更新 更多