-1

我有这样的结构:

<a href="some.jpg"><img src="other.jpg" onclick="someAction(this);"></a>
<a href="some2.jpg"><img src="other2.jpg" onclick="someAction(this);"></a>
<a href="some3.jpg"><img src="other3.jpg" onclick="someAction(this);"></a>

当我尝试将 alert(this) 添加到 onclick 时,我得到 [object HTMLImageElement]

我需要调用这个 someAction 以获得来自页面其他部分的精确图像

这个怎么做?

4

3 回答 3

2

为每个图像元素添加一个id,并使用元素id调用函数,这样:

<a href="some.jpg"><img id="img1" src="other.jpg" onclick="someAction(this.id);"></a>
<a href="some2.jpg"><img id="img1" src="other2.jpg" onclick="someAction(this.id);"></a>
<a href="some3.jpg"><img id="img1" src="other3.jpg" onclick="someAction(this.id);"></a>

然后改变你的功能如下:

function someAction(senderId){
   var sender = document.getElementById(senderId);
   // ...use sender variable as you did before
}

现在您可以在页面中的任意位置调用相同的函数,例如:

<div onclick="someAction('img2')">Foo</div>"
于 2013-07-05T14:59:02.683 回答
0

你必须给你的图像一个id="some_id"然后在你的函数调用中引用它:

   onClick="someAction(document.getElementById(\"some_id\"))"
于 2013-07-05T15:00:22.520 回答
0

您需要传入对该<img/>元素的引用。有多种方法可以获取对 DOM 节点的引用(例如,document.getElementByIddocument.getElementsByTagNamedocument.getElementsByClassName等)。

例如:

var firstImg = document.getElementsByTagName('img')[0];
someAction(firstImg);

此外,您可能应该将click处理程序绑定到锚点而不是图像,因为浏览器可能会href在执行图像处理程序之前跟随锚点click

于 2013-07-05T15:07:39.107 回答