如何判断点击了哪张图片

时间:2014-08-05 06:37:16

标签: javascript html css

                var pic3 = document.createElement("IMG");
                pic3.setAttribute("src", "img/mutantpre.jpg");
                pic3.setAttribute("onclick", "display()");
                pic3.setAttribute("id", "mutantpre");
                pic3.setAttribute("height", "250px");
                pic3.setAttribute("width", "150px");
                document.getElementById("product4").appendChild(pic3);

我试图创建一个函数,在单击此图片时将所有图片设置为隐藏。但是从那个函数我不知道哪个被点击了。我如何弄清楚他们点击了哪一个获得了它的ID,以便我可以设置其他人的可见性。

4 个答案:

答案 0 :(得分:0)

var pic3 = document.createElement("IMG");
            pic3.setAttribute("src", "img/mutantpre.jpg");
            pic3.setAttribute("onclick", "display('mutantpre')");
            pic3.setAttribute("id", "mutantpre");
            pic3.setAttribute("height", "250px");
            pic3.setAttribute("width", "150px");
            document.getElementById("product4").appendChild(pic3);

通过在点击功能中传递相同的id,你可以做到这一点

答案 1 :(得分:0)

您也可以这样做

var pic3 = document.createElement("IMG");
                pic3.setAttribute("src", "#");
                pic3.setAttribute("onclick", "display()");
                pic3.setAttribute("id", "mutantpre");
                pic3.setAttribute("height", "250px");
                pic3.setAttribute("width", "150px");
                document.getElementById("product4").appendChild(pic3);

function display(){
   el = document.getElementsByTagName("img");
    for(var i =0;i<el.length;i++){
   el[i].addEventListener("click",function(e){

      alert("the clicked one's id is "+e.target.id);
    });
        }
}

<强> Check the working Fiddle

答案 2 :(得分:0)

显示功能:

function display(element){
    var list = document.getElementsByTagName("img");
    for(var i=0; i<list.length ; i++){
        list[i].style.opacity = "0";
    }

    element.style.opacity="1";
}

在您的代码中,您必须拥有:

 pic3.setAttribute("onclick", "display(this)");

实例
http://jsfiddle.net/W65yA/1/

答案 3 :(得分:0)

希望这有帮助!

var images = document.getElementsByTagName('img');
var activeImage = images[0]; // Assuming the first image is active at first
for(var i = 0; i < images.length; i++) {
    var image = images[i];
    image.onclick = function() {
           activeImage.classList.remove("active");
           this.classList.add("active");
           activeImage = this;
        }
}