jQuery从字符串获取图像链接

时间:2013-02-15 20:37:23

标签: jquery

嘿所有我想从一个包含一些HTML的字符串中获取png链接。

字符串如下所示:

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:语法错误,无法识别的表达式:

我会失踪什么?

1 个答案:

答案 0 :(得分: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