Javascript 检测从父项onclick事件中单击的子项

Javascript 检测从父项onclick事件中单击的子项,javascript,jquery,html,Javascript,Jquery,Html,我有一个包含许多img元素的表。该表注册onclick事件&当它接收到onclick事件时,我想确定单击了哪个img(如果有) 我知道我可以在每个img元素中放置一个onclick事件,然后我就知道它们是否被单击了,但这也涉及到编写大量传递相同信息的长行(重复代码-我的意思见下文) 那么,有没有办法查看onclick事件中传递的事件对象来确定单击了哪个img元素?如果没有,也许有办法进行碰撞测试/碰撞测试?或者你知道另一种方式 <table onclick="openslideshow(

我有一个包含许多img元素的表。该表注册onclick事件&当它接收到onclick事件时,我想确定单击了哪个img(如果有)

我知道我可以在每个img元素中放置一个onclick事件,然后我就知道它们是否被单击了,但这也涉及到编写大量传递相同信息的长行(重复代码-我的意思见下文)

那么,有没有办法查看onclick事件中传递的事件对象来确定单击了哪个img元素?如果没有,也许有办法进行碰撞测试/碰撞测试?或者你知道另一种方式

<table onclick="openslideshow( event, new Array("img1.png","img2.png","img3.png"), "Author SlideShow");">
    <tr>
        <td><img class="screenshot" src="img1.png"/></td>
        <td><img class="screenshot" src="img2.png"/></td>
        <td><img class="screenshot" src="img3.png"/></td>
    </tr>
</table>

使用
evt.target
。这将为您提供已单击的元素

如果您将一个变量设置为该值,您可以在将来使用它来获取
src
,如下所示:

var elem = evt.target,
    elemSrc = elem.src;
console.log( elemSrc );

您正在使用jQuery,因此可以使用烘焙事件内委派功能:

$('table').on('click', 'img', function () {
    //now `this` refers the the image being clicked
});
下面是一个演示:

请注意,
.on()
在jQuery 1.7中是新的,对于1.4.2和1.7之间的版本,您可以使用`.delegate():

下面是一个演示:

您还可以使用提供给事件处理程序的
事件
对象:

$('table').on('click', function (event) {
    //event.target is the initial target of the element
});

这里是一个演示:

您可以在jquery中执行以下操作,而不是在每个img元素上放置onclick:

$(document).ready(function()
{ 
     $("img.screenshot").click(function() 
     {
         openslideshow( $(this), new Array("img1.png","img2.png","img3.png"), "Author SlideShow");
     });
});
编辑:


考虑到Jasper的评论,您可以将
this
$(this)
传递给
openslideshow()
函数。但是您必须根据这一点调整openslideshow()函数中的操作。

使用jquery将是最好的选择

$("table img").bind("click",function(){

    // the clicked image is $(this)

    //get the href
    var clickedImageHref = $(this).prop("href");

});

@杰克:应该是的。但是使用jQuery内置的
on()
函数更容易,就像Jasper指出的那样。
event。我相信它会给你按键。例如,当使用鼠标
事件时,
对于左键单击返回
1
,对于鼠标滚轮单击返回
2
<代码>事件。目标是我认为你想要的<代码>事件。该事件通常用于确定按下了哪个键盘键。建议不错。但是,您正在将
$(this)
传递到
openslideshow
函数,而OP的代码正在传递
this
;它是DOM元素,而不是包含DOM元素的jQuery对象。
href
是一个属性,因此将执行
.attr('href')
。主要的区别(我相信)是
.attr()
返回一个相对于文档的基本url的值,
.prop()
返回整个url(比如
this.src
)。
attr()
不是被弃用了吗?@Purmou-nope,
.live()
从1.7开始就被弃用了(也许这就是你所想的)但是
.prop()
是在1.6
中作为显式检索属性值的方式引入的,而.attr()检索属性
:(此链接有一个很好的表,描述了何时使用每个函数)
$('table').on('click', function (event) {
    //event.target is the initial target of the element
});
$(document).ready(function()
{ 
     $("img.screenshot").click(function() 
     {
         openslideshow( $(this), new Array("img1.png","img2.png","img3.png"), "Author SlideShow");
     });
});
$("table img").bind("click",function(){

    // the clicked image is $(this)

    //get the href
    var clickedImageHref = $(this).prop("href");

});