很抱歉问了这个简单的问题,但我正在努力解决这个问题。尝试过谷歌,但每次都会给出不同的答案..
我想要鼠标点击时的 id 文本,例如我里面有表格
<td>In the last month, how often have you been upset because of something that happened unexpectedly?</td>
<td style="text-align: center;" ><img id="demo1" src="cross.png" alt="" height='20' width='20' onmousedown="dis_item(this.id);" /></td>
<td style="text-align: center;" ><img id="demo2" src="cross.png" alt="" height='20' width='20' onmousedown="dis_item(this.id);"/></td>
<td style="text-align: center;" ><img id="demo3" src="cross.png" alt="" height='20' width='20' onmousedown="dis_item(this.id);"/></td>
<td style="text-align: center;" ><img id="demo4" src="cross.png" alt="" height='20' width='20' onmousedown="dis_item(this.id);"/></td>
<td style="text-align: center;"><img id="demo5" src="cross.png" alt="" height='20' width='20' onmousedown="dis_item(this.id);"/></td>
当我点击img时,它会将id传递给JavaScript函数,并且我想检查用户点击了哪个img,为此我需要检查id.text,以便我可以在函数中进行比较,
这是我的 JavaScript 代码
function dis_item(imgId) {
// window.alert("test");
var text = document.getElementById(imgId).value;
window.alert("This is Test" + text);
document.getElementById(imgId).src = "tick.jpg";
}
请仅使用 JavaScript 为我提供建议,请不要使用 jQuery..
我想比较用户点击了哪个img id..以便我可以进行一些计算..
最佳答案
I am successful in passing the img id to the function.
图像没有“值(value)”,所以这不起作用:
var text = document.getElementById(imgId).value;
相反,使用以下方式获取图像标记中的某些属性:
var text = document.getElementById(imgId).getAttribute("attr");
关于javascript - 使用鼠标单击获取元素 id 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30448373/