var strHTML = "<div><img src='/fake/path/fakeImage.jpg'/><span id='target'>text to extract</span></div>";
var dom = $(strHTML);
var extractedText = dom.find("#target").text();
alert(extractedText);
当我将 HTML 字符串转换为 jQuery 对象时,jQuery 发出 GET 请求来检索图片,正如您在开发人员工具的网络选项卡中看到的那样。
如何将 HTML 字符串转换为 jQuery 对象而不从解析的字符串下载任何资源?
注:jQuery.parseHTML不返回 jQuery 对象,您不能使用 .find()例如。
最佳答案
我认为这是不可能的,因为它不是 jQuery(或 javascript)来加载图像,而是浏览器 - 一旦在 img 上设置了
元素浏览器将尝试下载它。src
属性
您可以做的一件事是在构建 dom 之前将元素名称从 img 更改为其他名称,或者将 src 属性更改为其他名称,例如:
// change the <img> elements to <my_img> to avoid image fetching
strHtml = strHtml.replace(/<img /gi, "<my_img ").replace(/<\/img>/gi, "</my_img>");
// or the 2nd alternative: change the src attribute of images
strHtml = strHtml.replace(/<img([^>]*?) src=/gi, "<img$1 my_src=")
// now its safe to parse into DOM - no images will be fetched
var dom = $(strHtml);
请注意,这个简单的“搜索和替换”可能会替换您想要的元素以外的文本,但这可能足以满足您的用例。
关于javascript - 阻止 jQuery 在解析 HTML 字符串时下载资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32364172/