简体   繁体   中英

Append and escape

How do I escape before appending? The following incorrectly appends

'<a here."="" goes="" string"="" title="Some " href="#">Hello</a>'

in the code:

$(function(){
    var t='Some "string" goes here.';
    var jqueryObj=$('#elem');
    jqueryObj.append('<a href="#" title="'+t+'">Hello</a>');
});

REVISED CODE AFTER EDIT

var $accounts=$('#accountList');
$accounts.find('li.accountList').remove();
for (var i = 1; i < data.o.a.length; i++) {
    $accounts.append('<li class="item displayAccount">'
    +'<input type="checkbox" checked="checked" class="cb" name="accounts[]" value="'+i+'" />'
    +'<span class="name">'+data.o.a[i].name
      +((data.o.a[i].e.length)?' <a class="displayError" href="#" title="'+escape(mkList(data.o.a[i].e))+'">Error</a>':null)
    +'</span>'
    +'</li>');
}
if(data.o.a[0].c.length) {$accounts.append('<li class="item displayAccount"><input type="checkbox" disabled="disabled" value="0"><span class="name">UNASSIGNED</span></li>');}
$accounts.find('a.displayError').displayError();

jQuery has a nice syntax for creating elements safely:

$('<a>', {
    href: '#',
    title: t,
    text: 'Hello'  // Replace `text` with `html` if you need to.
}).appendTo(jqueryObj);

Your code relies a lot on strings, so I did what I could, but it could be made prettier:

for (var i = 1; i < data.o.a.length; i++) {
    var $li = $('<li class="item displayAccount"></li>');
    var $input = $('<input type="checkbox" checked="checked" class="cb" name="accounts[]" />').val(i).appendTo($li);
    var $span = $('<span class="name"></span>').appendTo($li);

    if (data.o.a[i].e.length) {
        $('<a class="displayError" href="#">Error</a>').attr('title', mkList(data.o.a[i].e)).appendTo($span);
    }

    $li.appendTo($accounts);
}

I figured I'd offer a different answer than Blender just in case you don't want to use that method.

function escapeQuotes(str){
    return str.replace(/"/g, '&quot;');
}

Will replace double quotes with &quot; .

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