2013-02-15 54 views
1

嘿,我想從一個字符串中獲得png鏈接,該字符串中包含一些HTML。jQuery從字符串中獲取圖像鏈接

的字符串看起來是這樣的:

var thecode = '[caption id="attachment_1794" align="alignleft" width="210"] 
    <a href="http://www.website.com/wp-content/uploads/2012/10/Screen-Shot-2012-10-30-at- 
    8.52.48-AM.png"><img class="size-medium wp-image-1794" title="Difference between and 
    affiliate programs" src="http://www.website.com/wp-content/uploads/2012/10/Screen- 
    Shot-2012-10-30-at-8.52.48-AM-210x300.png" alt="Learn the and affiliate programs" 
    width="210" height="300" /></a> Learn the and affiliate programs[/caption]<p><span 
    style="font-size: small;">An article by CEO of AD, Inc. (AD®), has been published by 
    <a title="Learn the and affiliate programs" href="http://www.mmag.com/articles/85281" 
    target="_blank">M Magazine</a>. The article is titled: "Putting The Right Place." </span>'; 

我一直在試圖獲得通過jQuery代碼圖片鏈接:

var newString = $('a[href$=".png"]', thecode).attr('href'); 
console.log(newString); 

但是上面就返回SCRIPT5022的例子:語法錯誤,無法識別表達:

我會錯過什麼?

+0

我沒有這個錯誤,你使用的瀏覽器? – 2013-02-15 20:43:34

+0

我正在使用IE版本9 – StealthRT 2013-02-15 20:45:12

+0

你想獲得PDF或PNG嗎? – j08691 2013-02-15 20:45:44

回答

6

試試這個:

var thecode = '[caption id="attachment_1794" align="alignleft" width="210"] <a href="http://www.website.com/wp-content/uploads/2012/10/Screen-Shot-2012-10-30-at-8.52.48-AM.png"><img class="size-medium wp-image-1794" title="Difference between and affiliate programs" src="http://www.website.com/wp-content/uploads/2012/10/Screen-Shot-2012-10-30-at-8.52.48-AM-210x300.png" alt="Learn the and affiliate programs" width="210" height="300" /></a> Learn the and affiliate programs[/caption]<p><span style="font-size: small;">An article by CEO of AD, Inc. (AD®), has been published by <a title="Learn the and affiliate programs" href="http://www.mmag.com/articles/85281" target="_blank">M Magazine</a>. The article is titled: "Putting The Right Place." </span>'; 

var newString = $('<div>'+ thecode + '</div>'); 
console.log($('a[href$=".png"]',newString).attr('href')); 

jsFiddle example

+0

AH,所以這就是** **和** **的原因。謝謝j08691! – StealthRT 2013-02-15 20:49:14

+0

爲什麼字符串需要用'div'包裝? – JSuar 2013-02-15 20:50:12

+1

@JSuar由於jquery解析html的方式,它必須包裝在div中,否則它不會獲得所有元素。 jquery不能很好地處理頂層的文本節點。 – 2013-02-15 20:52:45