我的网站包含很多图像,这就是为什么我不能为每个图像提供ID,这将是繁琐的任务.我需要获取图像标记的source属性,但是如果没有ID我就无法做到.我确实尝试过attr()和getAttribute(),但它似乎对我不起作用.
我的守则
<img src="./images/image1.jpg" width='100' height='100' alt='Sample image' onClick='imageInfo(this);'>
<script>
function imageInfo()
{
alert(this.src);
}
</script>
Run Code Online (Sandbox Code Playgroud)
我试图得到图像标记的来源,但它不会来我也尝试过jsfiddle,但它不起作用.
尝试这样的事情.因为您已经传递了图像对象但未在函数中使用
<script>
function imageInfo(obj)
{
alert(obj.src);
}
</script>
Run Code Online (Sandbox Code Playgroud)
从小提琴,
function imageInfo(this)
{
alert('image');
alert(this.src);
}
Run Code Online (Sandbox Code Playgroud)
这是因为this是一个保留关键字.
function imageInfo (e)
{
alert('image');
alert(e.src);
}
Run Code Online (Sandbox Code Playgroud)
也onclick没有onClick,知道原因检查这个SO答案
检查这个小提琴