DDR
DDR

Reputation: 1322

Applying click function through delegate on selected div in jquery

What is the best way to add opposite of Not of jquery?

<div class="line-item">
<div class="thumb">
    Image goes here
</div>
<div class="title">
    Title goes here
</div>
<div class="destroy">
    Destroy Button goes here
</div>

here is the Java Script

$('div.line-item').delegate('div:not(".destroy")', 'click', function() {
alert('hi');
})

What i want is to apply "click" on just that div having .destroy class

here is the working Demo: http://jsfiddle.net/trVKF/110/

Upvotes: 0

Views: 82

Answers (5)

Anand Jha
Anand Jha

Reputation: 10724

Try this for binding the click event without using delegate.

 $('.line-item > .destroy').click(function(){
        //your code goes here
 });

DEMO

Upvotes: 1

wrxsti
wrxsti

Reputation: 3504

$('div.line-item').on('click', '.destroy', function() {
    alert('hi');
});

If you are using a newer version of jQuery.

Upvotes: 1

Konstantin K
Konstantin K

Reputation: 1317

would that achieve what you need ?

$('div.line-item').delegate('div:not(".destroy")', 'click', function() {
    alert('hi');
}).delegate(".destroy", 'click', function(){
    alert('bye');
})

http://jsfiddle.net/trVKF/112/

Alternatively:

$('div.line-item').delegate('div', 'click', function(e) {
    if($(e.target).is(".destroy")){
        alert("bye");
    }else{
        alert("hi");
    }
});

http://jsfiddle.net/trVKF/113/

Upvotes: 1

adeneo
adeneo

Reputation: 318302

Use a newer version of jQuery and do :

$('div.line-item').on('click', '.destroy', function() {
//    ^^ static parent | ^^ event | ^^ dynamic element bound to handler
    alert('hi');
});

Upvotes: 2

techfoobar
techfoobar

Reputation: 66693

You can use:

$('div.line-item').delegate('.destroy', 'click', function() {
    alert('hi');
})

as in this Demo

Upvotes: 1

Related Questions