jQuery解析HTML而不加载图像

PiT*_*ber 14 javascript ajax jquery image

我从其他页面加载HTML以从该页面提取和显示数据:

$.get('http://example.org/205.html', function (html) {
    console.log( $(html).find('#c1034') );
});
Run Code Online (Sandbox Code Playgroud)

这确实有效,但由于$(html)我的浏览器尝试加载205.html中链接的图像.我的域上不存在这些图像,因此我收到了很多404错误.

有没有办法解析页面,$(html)但没有将整个页面加载到我的浏览器?

Bhu*_*kka 19

使用正则表达式并删除所有<img>标记

 html = html.replace(/<img[^>]*>/g,"");
Run Code Online (Sandbox Code Playgroud)


Tho*_*rus 9

实际上,如果你查看jQuery文档,它说你可以将"所有者文档"作为第二个参数传递给$.

那么我们可以做的是创建一个虚拟文档,以便浏览器不会自动加载提供的HTML中存在的图像:

var ownerDocument = document.implementation.createHTMLDocument('virtual');
$(html, ownerDocument).find('.some-selector');
Run Code Online (Sandbox Code Playgroud)