使用JS选择元素

时间:2017-03-13 03:08:01

标签: javascript html

var displayedImage = document.querySelector('.displayed-img');
var thumbBar = document.querySelector('.thumb-bar');

btn = document.querySelector('button');
var overlay = document.querySelector('.overlay');

/* Looping through images */
for(var i=1;i<=5;i++){
  var newImage = document.createElement('img');
  newImage.setAttribute('src', "images/pic"+i+".jpg");
  thumbBar.appendChild(newImage);
}

function getPath(){
    var path = this.document.getAttribute('src').value;
}
newImage.onclick=function(){

    var path = newImage.getAttribute('src');
    console.log(path);
    displayedImage.setAttribute('src', path);
}

我尝试在单击图像时打印出路径,但它只返回newImage的最后一个值..但我有4张可以选择的图片

2 个答案:

答案 0 :(得分:0)

您必须在循环内为每个新元素设置事件侦听器。像这样:

var displayedImage = document.querySelector('.displayed-img');
var thumbBar = document.querySelector('.thumb-bar');

btn = document.querySelector('button');
var overlay = document.querySelector('.overlay');

/* Looping through images */
for(var i=1;i<=5;i++){
    var newImage = document.createElement('img');
    newImage.setAttribute('src', "images/pic"+i+".jpg");
    thumbBar.appendChild(newImage);

    // **************************************************
    newImage.onclick=function(){
        var path = this.getAttribute('src'); // instead of newImage use this
        console.log(path);
        displayedImage.setAttribute('src', path);
    }
    // **************************************************
}

function getPath(){
    var path = this.document.getAttribute('src').value;
}

注意:如果您计划在分配给i的函数中使用onclick,请考虑查看this

答案 1 :(得分:0)

为什么不将CSS类附加到每个图像元素并使用类名作为CSS选择器?像这样,

alongside