有没有办法防止在jQuery客观化的HTML片段中加载图像

tec*_*bar 6 javascript jquery dom

我有一个HTML片段,我通过jQuery客观化,目的是从中提取一些数据.这个片段有一些我不希望浏览器下载的图像资源.有没有办法做到这一点.

我当前代码的简化版本:

var html = '<p class="data">Blah Blah</p>...<img src="/a/b/...png">...<div>...</div>';

var obj = $(html); // this makes the browser download the contained images as well!!!

var myData = {
    item_1: obj.find('.data:first').text(),
    item_2: obj.find('.data2:first').text(),
    .... // and so on..
};
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 4

除非您认为字符串中存在src=对您重要的子字符串实例,否则您可以这样做:

html = html.replace(/src=/g, "data-src=");
Run Code Online (Sandbox Code Playgroud)

或者可能

html = html.replace(/src\s*=/g, "data-src=");
Run Code Online (Sandbox Code Playgroud)

...允许空白。这样,浏览器将看不到该src属性,也不会触发下载。

有时直接的方法是最好的。当然,如果您认为某些src=子字符串对于您尝试提取的内容可能很重要,那么......