jQuery 从字符串中获取图像链接

标签 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: Syntax error, unrecognized expression:

我会缺少什么?

最佳答案

试试这个:

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

关于jQuery 从字符串中获取图像链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14902943/

相关文章:

javascript - 如何将事件监听器添加到由 JavaScript 中的对象创建的 html

javascript - 从 javascript 中的方法传递数据

javascript - 检查是否设置了 Cookie,然后加载页面,否则重定向页面

javascript - 如何使用多个验证码获取验证码值?

Jquery 将一个父 div 悬停在它的 2 个孙子和 1 个子元素上

javascript - 在移动 View 中隐藏广告横幅

jquery - 使用 typescript 和 webpack 扩展 jQuery

javascript - 跨域iframe实时url检测

javascript - 当 AngularJS 中没有 ngRepeated 时,如何在我的 DOM 中排序?

javascript - $ 在使用 setinterval 时未发现错误