Reputation: 73
I have a question when i develop my html with javascript.
What finally I want in html is:
<div id="test">
<div onclick="alert("it's a test.")">Show</div>
</div>
But in code I want it be realized like this:
<div id="test"></div>
<script>
var tmp="it's a test.";//be careful, there must be a single quote in this variable
$('#test').append("<div onclick='alert(\" "+tmp+" \")'>Show</div>");
</script>
In firebug it shows:
<div id="test">
<div ")'="" test.="" a="" s="" onclick="alert(" it">Show</div>
</div>
So i think it's an escaping problem. But I think it has minimum 3 levels of depth. Anyone can help me? Thanks!
Upvotes: 6
Views: 15545
Reputation: 382092
Don't use jQuery to write inlined script. Replace
$('#test').append("<div onclick='alert(\" "+tmp+" \")'>Show</div>");
with
$('<div>').click(function(){ alert(" "+tmp+" ") }).text('Show').appendTo('#test');
This way
temp
), you don't need to put it in the global scope, it can be in the scope of the element additionTo answer your question in comment, you can either
eventData
argument of jQuery's click function.Example of using jQuery's eventData
argument :
var names = ['A', 'B'];
for (var i=0; i<names.length; i++) {
$('<div>').text('link '+(i+1)).click(names[i], function(e) {
alert('Name : ' + e.data);
}).appendTo(document.body);
}
Upvotes: 5
Reputation: 1041
Backslashes can be used to escape special characters
<div id="test"></div>
<script>
var tmp=\"it's a test.\";//be careful, there must be a single quote in this variable
$('#test').append("<div onclick='alert(\" "+tmp+" \")'>Show</div>");
</script>
That should work hopefully, if not it should help you get started
Upvotes: 2
Reputation: 38102
An easier way is to append new div
to your #test
then use event delegation to bind click event for your newly added div
like this:
$('#test').append("<div class='newDiv'>Show</div>");
$('#test').on('click','.newDiv',function() {
alert("it's a test.");
});
Upvotes: 1