Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 获取已单击对象的ID或类_Jquery - Fatal编程技术网

Jquery 获取已单击对象的ID或类

Jquery 获取已单击对象的ID或类,jquery,Jquery,我正在尝试制作一个简单的插件,因此当用户点击照片时,他会得到一张更大的照片(因为所有照片都比真实照片小)。我的问题是,当用户点击body或html时,这张更大的照片怎么能关闭,但如果点击照片,它不应该关闭?可能应该是这样的: $('body, html').click(function() { if(clickedOnPhoto) //do nothing else //close the photo }) 将为您提供已单击的最叶元素。您可以将其包装

我正在尝试制作一个简单的插件,因此当用户点击照片时,他会得到一张更大的照片(因为所有照片都比真实照片小)。我的问题是,当用户点击
body
html
时,这张更大的照片怎么能关闭,但如果点击照片,它不应该关闭?可能应该是这样的:

$('body, html').click(function() {

   if(clickedOnPhoto)

      //do nothing

   else

     //close the photo

})
将为您提供已单击的最叶元素。您可以将其包装到
$()
中,通过jQuery执行您喜欢的任何类/属性检查

$(document).click(function(e){
    var id = e.target.id; // get the id attribute of the target of the click
    if( id === 'yourDivId' ) {
        // photo was clicked
    } else {
        // something else was clicked
    }
});

而不是检查目标是什么并决定做什么;您可以将
单击
事件处理程序添加到
文档
元素以关闭大照片,并将
单击
事件处理程序添加到大照片中,以停止
单击
事件的传播,使其不会到达
文档
元素:

$('#photo-container').on('click', '.big-photo-elements', function (event) {
    //stop the event from propagating normally so that it does not reach the `document` element
    event.stopPropagation();
});

$(document).on('click', function () {
    //run code to close big photos, this will not be triggered if a user clicks on the big photo
    $('.big-photo-elements').hide();
});

@阿姆诺蒂安:他想得到点击目标的
id
,并在调整其大小之前检查它是否是放大的图像。太好了,用class代替id怎么样?你是说
e.target.className
,它返回一个包含class属性的字符串(如果有多个class,通常是空格分隔的)@PaulPro:哦,是的,我的错了。谢谢你指出这一点。+1我认为
stopPropagation
方法是一种更好的方法。简单又低维护。@Jasper:实际上我更喜欢这种方法。你能给我解释一下写的是什么吗?无论如何,谢谢你。圣诞快乐。