更改src属性后图像不显示

时间:2014-06-29 09:18:58

标签: javascript html javascript-events

与我在src函数中将rollEvent更改为值后的标题一样,图像不会更改。当我将display.src的值打印到控制台时,它是正确的。但实际文档不会使用display_box类更改src标记的img值。我在这里错过了什么吗?

jsfiddle.net/bNL5C/3/

window.onload = function eventsLoad (elem, display) {
    elem = document.getElementsByClassName('images');
    display = document.getElementsByClassName('display_box');
    function rollEvent(e) {
        var sourceURL = this.src;
        console.log(sourceURL);
        display.src = sourceURL;
        console.log(display.src);
    };
    console.log(elem);
    console.log(display);
    for (var i = 0; i < elem.length; i++) {
        elem[i].addEventListener('mouseover', rollEvent, false);
        console.log('Added event listener to ' + elem[i]);
    };
}

2 个答案:

答案 0 :(得分:1)

getElementsByClassName返回NodeList,因此您应该更改display.src = sourceURL

function rollEvent(e) {
    var sourceURL = this.src;
    display[0].src = sourceURL; // <--- change here
    console.log(display.src);
};

演示:http://jsfiddle.net/bNL5C/4/

或改为使用display = document.querySelector('.display_box');

答案 1 :(得分:0)

试试这个......改变:

document.getElementsByClassName returns an array - display is a list. Try changing
    display.src = sourceURL;

要:

display[0].src = sourceURL;