Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript替换图像源_Javascript_Image_Class_Attributes_Edit - Fatal编程技术网

Javascript替换图像源

Javascript替换图像源,javascript,image,class,attributes,edit,Javascript,Image,Class,Attributes,Edit,我试图更改网页中src标记的内容(不更改HTML/命名结构) 我的代码目前看起来像这样: 什么都没有 我需要更改这个img标签的src 我的javascript目前看起来是这样的 函数changeSource(){ var image=document.querySelectorAll(“img”); var source=image.getAttribute(“src”).replace(“placeHolder.png”、“01.png”); setAttribute(“src”

我试图更改网页中src标记的内容(不更改HTML/命名结构)

我的代码目前看起来像这样:


什么都没有

我需要更改这个img标签的src 我的javascript目前看起来是这样的


函数changeSource(){
var image=document.querySelectorAll(“img”);
var source=image.getAttribute(“src”).replace(“placeHolder.png”、“01.png”);
setAttribute(“src”,来源);
}
changeSource();


我不知道为什么它不起作用,但我希望有人能做到:D

将您的函数更改为:

function changeSource() {
    var image = document.querySelectorAll("img")[0];
    var source = image.src = image.src.replace("placeholder.png","01.png");
}
changeSource();
querySelectorAll
返回一个数组。我通过执行
[0]
获得了第一个


但是你应该使用
document.getElementById('id of img here')
来定位一个特定的
这些翅膀是什么???顺便说一下,我使用了^。我更新了你的问题并删除了翅膀。:)
document.querySelectorAll()
返回节点列表,您需要使用
querySelector
,或者只访问第一个(或任何其他)元素,例如
image[0]
。但是图像的src是
image/placeholder.png
,它将被更改为:
01.png
,它应该是
image/01.png
,这回答了它,多亏了大家,我狠狠地揍了一顿:不过关于这个答案,我还有一个问题要问。当图像编号[0]未确定时,如何应用相同的选择器和格式?请使用
document.getElementById(“图像id”)
我无法使用id,因为我正在编辑的网页设置为通过php生成自己的id,因此在调用img元素时,id总是随机化的。有没有一种方法可以使用[0]但将其用作[“任意数字”]不像CORS那样,而是使用正确的语法这是一种有趣的方法来使用get/setAttribute,我不知道:D我可能会使用它,非常感谢
<script type="text/javascript">

function changeSource() {

    var image = document.querySelectorAll("img");
    var source = image.getAttribute("src").replace("placeHolder.png", "01.png");
    image.setAttribute("src", source);
}

changeSource();

</script>
function changeSource() {
    var image = document.querySelectorAll("img")[0];
    var source = image.src = image.src.replace("placeholder.png","01.png");
}
changeSource();
function changeSourceAll() {
    var images = document.getElementsByTagName('img');
    for (var i = 0; i < images.length; i++) {
        if (images[i].src.indexOf('placeholder.png') !== -1) {
            images[i].src = images[i].src.replace("placeholder.png", "01.png");
        }
    }
}
changeSourceAll();
function changeSource() {
   var img = document.getElementsByTagName('img')[0];
   img.setAttribute('src', img.getAttribute('src').replace("placeHolder.png", "image.png"));
}