我在页面上有一些图片,当我单击这些图片时,它们试图以模式方式打开。我正在使用document.getElementById()
尝试定位已单击的图像ID。到目前为止,我已经尝试创建一个函数,该函数将单击的ID转换为变量以传递给document.getElementById(variable)
,但这似乎不起作用。有没有更好的方法来解决这个问题?
function open_clicked(clicked_id) {
var current_id = clicked_id;
}
document.getElementById(current_id);
<img id="Elk" src="images/elk.png" alt="Elk" onclick="open_clicked(this.id)">
<img id="Deer" src="images/deer.png" alt="Deer" onclick="open_clicked(this.id)">
而不是将this.id
作为参数传递给open_clicked
函数,您可以仅将this
作为参数传递给访问被单击元素的方法。
这是一个简单的演示。
function open_clicked(currImg) {
// you do not need to call document.getElementById again
// currImg is the img element that was clicked
var currentImgId = currImg.getAttribute("id")
console.log(currentImgId)
}
<img id="Elk" src="images/elk.png" alt="Elk" onclick="open_clicked(this)"/>
<img id="Deer" src="images/deer.png" alt="Deer" onclick="open_clicked(this)"/>