views:

248

answers:

2

This is what I've tried:

html:

<div id="container">
  <p>a paragraph</p>
</div>
<button>replace with link</button>

script:

$(document).ready(function() {

     $("a.foo").click(function() {
        alert('hello world');
     });

     function foo() {
        alert('hello world');
     }

     $("button").click(function () {
        // neither of these work
        // $("#container p").replaceWith('<p><a href="#" class="foo" >trigger function<\/a><\/p>');
        // $("#container p").replaceWith('<p><a href="#" onclick="foo();return false" >trigger function<\/a><\/p>');
     });

});
+2  A: 

I think you are looking for live.

http://docs.jquery.com/Events/live

Replace this

$("a.foo").click(function() {
        alert('hello world');
});

with

$("a.foo").live('click', function() {
        alert('hello world');
});

and do your replacement like

$("#container p").replaceWith('<p><a href="#" class="foo" >trigger function<\/a><\/p>');
Daniel A. White
awsome, thanks so much
FFish
No problem.....
Daniel A. White
A: 

Why are you using .replaceWith()? All you need is .html():

$("button").click(function() {
  $("#container p").html('<p><a href="#" class="foo" >trigger function</a></p>');
});
Mala
replaceWith replaces the entire matched element, not what's inside it.
Andrew Koester
Ah indeed - so strip off the <p> and </p> of my string and it still does what he wants i think
Mala