获取单击对象的ID或类

时间:2011-12-23 21:52:02

标签: jquery

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

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

   if(clickedOnPhoto)

      //do nothing

   else

     //close the photo

})

3 个答案:

答案 0 :(得分:6)

试试这个:

$(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
    }
});

答案 1 :(得分:2)

而不是检查目标是什么并决定做什么;您可以向click元素添加document事件处理程序以关闭大照片,并为停止传播click事件的大照片添加click事件处理程序它没有到达document元素:

$('#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();
});

答案 2 :(得分:0)

event.target将为您提供已点击的最多元素。您可以将其包装到$()中,以通过jQuery

执行您喜欢的任何类/属性检查
相关问题