2013-04-02 51 views
6

我有一個HTML片段,我通過jQuery客觀化從中提取一些數據。這個片段有一些我不希望瀏覽器下載的圖像資源。有沒有辦法做到這一點。有沒有辦法阻止加載圖像在jQuery對象化的HTML片段

的簡化版本的我當前的代碼:

var html = '<p class="data">Blah Blah</p>...<img src="https://stackoverflow.com/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.. 
}; 

回答

4

除非你認爲會有您所關心的字符串中的子src=的情況下,你可以這樣做:

html = html.replace(/src=/g, "data-src="); 

或可能

html = html.replace(/src\s*=/g, "data-src="); 

...允許空白。這樣,瀏覽器將不會看到src屬性,並且不會觸發下載。

有時直接的方法是最好的。當然,如果您認爲可能存在src=子串,這對您要提取的內容而言很重要,那麼...

+1

謝謝。不要以爲我需要提取的數據中的任何地方都有'src ='。這應該工作。 (不敢相信我想不出這個!) – techfoobar

+0

工作完美。 :) – techfoobar

+0

這個答案聽起來很熟悉。嗯[是啊](http://stackoverflow.com/questions/2302129/construct-a-dom-tree-from-a-string-without-loading-resources-specifically-image/2302157#2302157);) –

相關問題