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

escaping, html, javascript, jquery

Solution

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

- use an intermediate closure to enclose the value at the time of looping (example here)

- or use the `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

Problem

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!

Original source