如何识别在Jquery中点击的DIv

时间:2014-04-07 04:48:26

标签: javascript jquery

我需要知道单击事件在我的文档中发生的位置,我有一些div,当我按下cntrl键并单击它们时会发生一些事件,我只需要知道如何识别被点击的div,是否可以在document.click中概括它们fn就像我尝试过的那样。 以下是我试过的样本

HTML

<div class="DivOne">Div1</div>
<div class="DivTwo">Div2</div>
<div class="DivThree">Div3</div>

Jquery的

   $(document).bind("click", function (e) {
    if (e.which == '17') {
        alert(e.parent);//I need to know Whether Click happens on divOne or Two or on No Mans Land
        }
    });

3 个答案:

答案 0 :(得分:3)

您可以使用e.target.is()功能来实现您的目标。

尝试,

   $(document).bind("click", function (e) {
     if($(e.target).is('.DivOne')){
       alert('Div one has been clicked..!')
     }
   });

答案 1 :(得分:2)

$("div").click(function (e) {
    var classOfDiv = this.className;
    // do stuff depending on what class
});

答案 2 :(得分:0)

您可以选择类或类似的ID

$("#DivOne").click(function (e) {
if (e.which == '17') {
    alert(e.parent);//I need to know Whether Click happens on divOne or Two or on No Mans Land
    }
});

或类

$(".DivOne").click(function (e) {
if (e.which == '17') {
    alert(e.parent);//I need to know Whether Click happens on divOne or Two or on No Mans Land
    }
});

或者,您可以遍历页面上的所有div并测试单击

$("div").each(function () {
    $(this).click(function() {
        var divClass = $(this).attr('class');
        alert("You clicked on " + divClass);
    });
});

<强> Fiddle