Link to home
Start Free TrialLog in
Avatar of stephaneeybert
stephaneeybert

asked on

jquery on click handler in an each loop

Dear all,

I don't know why but my on click handler does not work.

It is never triggered.

I also tried with a

$(this).click(

but it was the same.

The loop works fine and the elements are removed.

But I would like to remove only the one element that has been clicked on, not all of them.

// Clear the displayed content
      $(this).find('span.elearning_question_dropped_content').find('.elearning_question_dropped_item').each(function(i, element) {
alert("This alert displays the element fine " + element);
// TODO why the on click does not work?
        $(this).bind(
          "click",
          function() {
alert('This alert is never displayed... why..?');
alert('clicked on id ' + element.attr('id'));
        });
        $(this).html('');
        $(this).remove();
      });

Open in new window

Avatar of Albert Van Halen
Albert Van Halen
Flag of Netherlands image

You're binding a function to the click event of the element in the foreach loop (it doesn't get triggered) and after that the element is removed.

In order to trigger an event you have to use the trigger or triggerHandler method.
Just move the remove method into your function bound to the click event.

See code
// Clear the displayed content
      $(this).find('span.elearning_question_dropped_content').find('.elearning_question_dropped_item').each(function(i, element) {
    $(this).bind("click", function() {
        $(this).remove();
    });
});

Open in new window

Avatar of stephaneeybert
stephaneeybert

ASKER

Hi Albert,

Here is how I did:
      $(this).find('span.elearning_question_dropped_content').find('.elearning_question_dropped_item').each(function(i, element) {
        $(this).bind(
          "click",
          function() {
          $(this).html('');
          $(this).remove();
        });
      });

And it works fine.

But I don't know why it now works and not before.

Why the alert was not triggered before ?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Albert Van Halen
Albert Van Halen
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The first click does not delete the element.

It seems like the first click gets the focus.

Then fron the second click on the clicks do delete the elements.

How to fix this so as to have the first click delete the clicked element ?
Okay, I will remove the clearing of content.

Thanks for the explanation.
Hi Albert, sorry for the delay, I'm on holidays in Egypt..

If you happen to have a clue about the focus issue I mentioned feel free :-)