I got a question in theory... I'm currently at work and can't try it..
If I have the following code :
stuff = '<button onclick="alert(' + "'Test');" + 'my Button</button>';
$("container").html(stuff);
When I click on my new button, will my script work? And will my button be added?
I didn't get any result on JsFiddle...
3 Answers 3
Supposing you fix the selector "container" and the unclosed tag, it should work.
But that's not how you bind events properly using jQuery.
You should do this :
$("#container").empty().append(
$('<button>my Button</button>').click(function(){ alert("Test") })
);
2 Comments
$("#container").empty().appendTo(...). I believe this is what we want in this case to replace .html(...).append() instead of appendTo(), as I mistakenly said. After looking at jQuery docs all day you get these methods confused with each other...It would work if you closed the opening button tag correctly
stuff = '<button onclick="alert(' + "'Test');" + '">my Button</button>';
$("container").html(stuff); ^^
Also as pointed out in a comment your selector for container is probably wrong.
Most likely you want one of these 2 depending on if container is a class or id:
$(".container").html(stuff);
$("#container").html(stuff);
Comments
That would work, but you forgot to close your button tag.
stuff = '<button onclick="alert(\'Test\');">my Button</button>';
$("container").html(stuff);
$("container").replaceAll($("<button>my Button</button>").click(function () { alert("Test"); }));>.