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.
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();
});
ASKER
Hi Albert,
Here is how I did:
$(this).find('span.elearni ng_questio n_dropped_ content'). find('.ele arning_que stion_drop ped_item') .each(func tion(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
Here is how I did:
$(this).find('span.elearni
$(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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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 ?
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 ?
ASKER
Okay, I will remove the clearing of content.
Thanks for the explanation.
Thanks for the explanation.
ASKER
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 :-)
If you happen to have a clue about the focus issue I mentioned feel free :-)
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
Open in new window