如何在我的情况下调用函数?

时间:2013-07-05 14:54:14

标签: javascript

我有这样的结构:

<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>

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

我需要从页面的其他部分调用此someAction来获取精确的图像

怎么做?

3 个答案:

答案 0 :(得分: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>"

答案 1 :(得分:0)

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

   onClick="someAction(document.getElementById(\"some_id\"))"

答案 2 :(得分:0)

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

例如:

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

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

相关问题