简体   繁体   中英

How can I Identify the DIv which got clicked in Jquery

I need to know where the click event happens in my document, i Have some divs , and when i press cntrl key and click on them some events will occur, i just need to know how to identify the divs which got clicked, is it possible to generalize them in document.click fn Like what i have tried. Here is a sample of what i have tried

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

You can use e.target along with .is() function to achieve what you want.

Try,

   $(document).bind("click", function (e) {
     if($(e.target).is('.DivOne')){
       alert('Div one has been clicked..!')
     }
   });
$("div").click(function (e) {
    var classOfDiv = this.className;
    // do stuff depending on what class
});

You can select classes, or ids like so

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

or a class like

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

Alternately you can loop through all divs on the page and test for a click

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

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM