简体   繁体   中英

Jquery Append remove the escaped quote

I've a Javascript with Jquery.

http://jsfiddle.net/P5gD7/3/

var libelle = 'tes\'te';
var id = 1;
var toAdd = "<input type='text' name='choix[" + id + "]' value='" + libelle + "' />";
$("#test").append(toAdd);

The problem is when I've a quote in "libelle" variable (i've escaped this quote), when I use append, Jquery put only tes in the "value" attribute. I have to do with simple quote. For info an alert(toAdd) return me the entire input with no errors.

Any ideas ?

Thanks

If you use jQuery to create the element for you through properties instead of string manipulation you can avoid these kind of problems:

var libelle = 'tes\'te';
var id = 1;
$('<input />', {
    type: 'text',
    name: 'choix[' + id + ']',
    value: libelle
}).appendTo('#test');

Example fiddle

One approach here is to create the element, then set the value on that element. These can be chained together something like:

var libelle = "tes'te";
var id = 1;
var toAdd = "<input type='text' name='choix[" + id + "]' />";

// create the element, show and finally set the value (.val)
$(toAdd).appendTo("#test").val(libelle);

See The Fiddle Here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM