How can I use jQuery's replaceWith() function to make a href link trigger a function?

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>');
     });

});

Answers


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>');

Need Your Help

How to declare array as a data member of a class in JavaScript

javascript html

Hello all I am working in javascript and html5.I want to ask that how can we add an array as a data member of a class in javascript

Execute multiple MySQL queries

php mysql sql

I have 2 sql queries to execute, but I want it to execute all or if error in one query then dont execute any. I'm using php. I used to use try and catch in .NET but I'm new to php.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.