【问题标题】:Making sure the src attribute has http:确保 src 属性具有 http:
【发布时间】:2014-02-25 00:26:52
【问题描述】:

我正在使用这个 jquery 脚本来导入部分维基百科文章,但是我遇到了一个问题,当这个脚本将一个图像标签放在一起时,它会去掉“http:”(或者更确切地说,它不是首先有?)来自 src 属性。如何确保每个 img 标签在 src 属性的开头都有 http: 而不添加另一个,如果它已经存在?

这是我正在使用的:

https://gist.github.com/steren/704540

具体来说,这是添加图像的内容(但省略了“http:”):

//get images of right side table
var rightTableImages = content.find('table a.image img');        
//append first image to main container  
wikiContainer.append($(rightTableImages).first().removeAttr('srcset').removeAttr('height').removeAttr('width').addClass("imageForArticle").wrap('<div class="wikipediaLogo"></div>').parent());

我尝试通过在上面添加.addClass("imageForArticle") 来为图像添加一个类,然后尝试这样做:

$('. imageForArticle').attr('src', function(index, src) {
return 'http:' + src;
});

但是当我这样做时,如果一个页面中有多篇文章,有时在我重新加载页面时会在其中添加一个额外的 http:。

【问题讨论】:

  • 你为什么需要它?像//example.com/ 这样的网址是perfectly valid

标签: jquery attributes wikipedia src


【解决方案1】:

试试

$('. imageForArticle').attr('src', function (index, src) {
    return (src.indexOf('http') == 0) ? src : 'http:' + src;
});

如果src.indexOf('http') == 0以http开头,则返回相同的,否则添加http:


或者
$('. imageForArticle').not('[src^="http"]').attr('src', function (index, src) {
    return 'http:' + src;
});

从 http $('. imageForArticle').not('[src^="http"]') 排除带有 src 的结果

【讨论】:

  • 克拉^ 的意思是“开始于”吗?谢谢你,这很好。
  • @user2219915 是阅读Attribute Starts With Selector ^
  • ../image.jpg这样的相对URL呢?您的代码会将其更改为 http:../image.jpg,这是不对的。
  • 我从维基百科中提取图片,所以没有一个是相对网址。如果我来到它,我会穿过那座桥。
【解决方案2】:

试试这个:

$('. imageForArticle').attr('src', function (index, src) {
    return (src.indexOf('http') < 0) ? src : 'http:' + src;
});

【讨论】:

    猜你喜欢
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2018-01-01
    • 1970-01-01
    相关资源
    最近更新 更多