views:

57

answers:

1

I'm having an issue with this script and for the life of me I can't figure out what's wrong with it. Quick run through what I have:

The HTML:

<ul>
    <li id="wildcard_1">
        <div>
            <a href="#">test</a>
        </div>
    </li>
</ul>
<a href="#" class="reset">reset</a>

The jQuery:

// Main function
$("[id^=wildcard_]").children('div').children('a').click(function() {
    $(this).replaceWith($(this).text());
});

// Temporary reset function
$("a.reset").click(function() {
    $("[id^=wildcard_]").children('div').wrapInner('<a href="#"></a>');
});

The "test" link works as it's supposed to the first time is is being clicked -- it is being transformed into plain text). In order not to paste the bulk of the script here, I have created a temporary function that will wrap the contents of the div, transforming the "test" plain text back into a link. And this is where it goes haywire -- the .click() listener of the first function will not trigger on this dynamically created link anymore and FireBug isn't throwing any errors nor warnings.

You can also see this live on JSfiddle: http://jsfiddle.net/rWz69/

Any help on this would be more than appreciated !

+6  A: 

You can use .live() handler, like this:

$("[id^=wildcard_] > div > a").live("click", function() {
  $(this).replaceWith($(this).text());
});

Here's your fiddle example updated/working with the above code :)

Nick Craver
Asked 1 minute ago, answered 23 seconds ago. I'm pretty sure you're a cyborg, Nick.
Robert
Simply brilliant, and damn fast too ! Funny thing is, the first thought that crossed my mind after seeing your answer was "God, my selector is ugly" :) Anyways, if it's not too much to ask, since my approach almost drove me insane, could you please explain in just a few words why exactly it didn't work so I can avoid it in the future ? Many thanks, buddy !
FreekOne
+1 for answering so dang fast and correctly might I add.
Randall Kwiatkowski
@FreekOne - Sure! a `.click()` attaches a click handler to the elements the selector finds *at the time*, that's the important bit, **to the elements**. If new elements are added...well tough luck they don't get a handler. `.live()` instead attaches an event listener on `document` that listens for the `click` to bubble up, so it works on current and future elements just the same :)
Nick Craver
Ah, I see ! Thanks a bunch, again ! :)
FreekOne
@FreekOne - welcome :)
Nick Craver