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!
' End first quotation which uses single quotes. " Start second quotation, using double-quotes. ' Quoted character. " End second quotation, using double-quotes.
Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
There are two ways to escaping the single quote in JavaScript. 1- Use double-quote or backticks to enclose the string. Example: "fsdsd'4565sd" or `fsdsd'4565sd`. Note: use a double backslash.
To escape a single or double quote in a string, use a backslash \ character before each single or double quote in the contents of the string, e.g. 'that\'s it' . Copied!
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);
}
Demonstration
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
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.");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With