سؤال

I am trying to change the contents of the src tag within a web page (without changing the HTML/naming structure)

My code looks something like this at the moment:

....

<div class="main">
    <button>
        <img src="image/placeHolder.png"/>
        <div>the nothing</div>
    </button>
</div>

....

I need to change the src of this img tag My javascript looks like this at the moment

....

<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>

....

I have no idea why it isn't working but I'm hoping someone out there does :D

هل كانت مفيدة؟

المحلول

Change your function to:

function changeSource() {
    var image = document.querySelectorAll("img")[0];
    var source = image.src = image.src.replace("placeholder.png","01.png");
}
changeSource();

querySelectorAll returns an array. I took the first one by doing [0].

But you should use document.getElementById('id of img here') to target a specific <img>

If you want to target all <img> that has placeholder.png.

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"));
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top