Luc
Luc

Reputation: 73

How to escape single quotes or double quotes within jquery's append(), onclick(), alert() at one time?

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

Answers (3)

Denys S&#233;guret
Denys S&#233;guret

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

  • you don't eval the code on click
  • syntax errors are direcly detected
  • you won't have quote escaping problem
  • the code is more readable
  • you'll have a direct binding, without useless selector resolution
  • when you need a variable (for example temp), you don't need to put it in the global scope, it can be in the scope of the element addition

To answer your question in comment, you can either

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

Upvotes: 5

Brian H
Brian H

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

Felix
Felix

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

Related Questions