bumbumpaw
bumbumpaw

Reputation: 2530

Class use in different element (other jQuery selector not working)?

Can someone explain to me or point me to other solution for this:

class fruit is in two different tag element, and one element has add class use in jquery selector, but the alertbox is not showing. ("add is clicked")

 <table>
        <tr>
            <td><a href="#" class="add fruit">Apple</a></td>
            <td><a href="#" class="fruit">Apple 2</a></td>
        </tr>
        <tr>
            <td><a href="#" class="add fruit">Banana</a></td>
            <td><a href="#" class="fruit">Banana 2</a></td>
        </tr>
    </table>

Also when i clicked the Apple link, i want the two alert box to show. see this FIDDLE for demo.

$('.add').off("click").on("click", function () {
    alert("add is clicked");
});

$('.fruit').off("click").on("click", function () {
    alert("fruit is clicked");
});

Upvotes: 0

Views: 50

Answers (5)

keols
keols

Reputation: 31

When you use ".off('click')" in 2, you remove the event handler added in 1.

1. ---

$('.add').off("click").on("click", function () {
 alert("add is clicked");
});

2. ---

$('.fruit').off("click").on("click", function () {
 alert("fruit is clicked");
});

Put it in reverse order:

$('.fruit').off("click").on("click", function () {
 alert("fruit is clicked");
});

$('.add').off("click").on("click", function () {
 alert("add is clicked");
});

Read this: http://api.jquery.com/off/

Upvotes: 0

Naveen Chandra Tiwari
Naveen Chandra Tiwari

Reputation: 5123

You are already doing it correct, just remove "off".

    $('.fruit').on("click", function () {
     alert("fruit is clicked");

   });
  $('.add').on("click", function () {
     alert("add is clicked");
  });

Upvotes: 1

LJᛃ
LJᛃ

Reputation: 8123

The off method unbinds all prior bound click events. I think you would be better off putting these events into one handler.

$('.fruit').click(function () {
    if ($(this).hasClass('add'))
        alert("add is clicked");
    else
        alert("fruit is clicked");
});

Upvotes: 0

peterjb
peterjb

Reputation: 819

In your Fiddle, you are using off("click") before the on("click", function...). The first off clears all previously registered click handlers. So you are turning off the add click handler before you add the fruit click handler

Upvotes: 0

Marcel Grolms
Marcel Grolms

Reputation: 418

Don't really know what you did, but i think you would like to have this results.

$('.add').click(function () {
    alert("add is clicked");
});
$('.fruit').click(function () {
    alert("fruit is clicked");
});

Look here :

http://jsfiddle.net/x957pbrr/1/

Upvotes: 0

Related Questions