【问题标题】:Replace certain img src with another via javascript通过javascript将某些img src替换为另一个
【发布时间】:2016-06-17 00:43:08
【问题描述】:

src 是特定的东西时,我正在尝试替换我页面上所有图像的所有src

$("img").each(function(i, elem){
    if ($(this).attr("src") == "/images/oldimage.png"){
        console.log("yay!") //this doesn't log anything
        $(this).attr("src", "/images/mynewimage.png");
    }
});

我认为上面的方法可行,但似乎不行。它没有找到任何与我的if 语句匹配的东西,我用console.log 测试了它,但是有很多img 应该匹配。

【问题讨论】:

  • 你测试过$(this).attr("src") 的实际值是多少(通过记录它)?
  • @Quentin 好主意。原来它没有在this 中找到我需要的图像,但我的目标是像这样的img<img class="cx-label-indicator indicator-right" height="14" width="14" src="/images/resources/indicators/hd/ind-triangle-down-red.png"> 不应该这样吗?
  • 对象的src 值将包含完整路径,要从源中获取实际的src,请尝试img.getAttribute('src')
  • “原来它没有找到我需要的图像”——它找到了什么?什么都没有?
  • @Quentin 它正在寻找其他带有 img 的图像,但不是我需要的图像。认为它们可能会在我的脚本之后添加到页面中。

标签: javascript jquery html image


【解决方案1】:

您可以使用 getAttributesetAttribute 来实现。

var aExample = document.querySelectorAll("img");
for(var i = 0; i < aExample.length; i += 1) {
    if(aExample[i].getAttribute("src") === "images/old.png") {
        aExample[i].setAttribute("src", "images/new.png");
    };
};

【讨论】:

    猜你喜欢
    • 2014-05-07
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    相关资源
    最近更新 更多