简体   繁体   中英

Escape Single Quote Twice in Javascript

I come across the situation that I need to use the escape quote twice. Specifically, I need to put an variable in javascript function with single quotes, but the variable itself also has single quotes. Details can be seen below, the problem line is the one with class "tile_name":

template = '' +
    '<div name="'+$("#add_tags :selected").text()+'" class="tile" id="newsCat_gp" >' +
        '<span onclick="this.parentNode.style.display = \'none\';" class="closebtn">&times;</span>' +
        '<div class="tile__name"><b><font size="2px">'+$("#add_tags :selected").text()+'</b></font>  <a id="newCat__'+$("#idx_newsCat").text()+'img" style="text-align: right; float: right;" href="javascript:toggle5(\'newCat__\'+$("#idx_newsCat").text()+\'\', \'img\', \'newCat__\'+$("#idx_newsCat").text()+\'img\');"><img src=  "{% static '/img/minus.png' %}"></a> </div>' +
        '<div class="tile__list" id="newCat__'+$("#idx_newsCat").text()+'" style="display: block;"></div>' +
    '</div>';

I want the results is

\'newCat__\'+$("#idx_newsCat").text()+\'\' 

becomes

'newCat__'+$("#idx_newsCat").text()+' ' 

like what in the tile_list class, and finally give the results of newCat__20,

where 20 is held by $("#idx_newsCat").text() .

Could anyone has the idea? Many thanks.

您不必在连接字符串的地方转义

javascript:toggle5(\'newCat__'+$("#idx_newsCat").text()+'\', \'img\', \'newCat__'+$("#idx_newsCat").text()+'img\');

maybe this will help

 var template = '' + '<div name="'+$("#add_tags :selected").text()+'" class="tile" id="newsCat_gp" >' + '<span onclick="this.parentNode.style.display = \\'none\\';" class="closebtn">&times;</span>' + '<div class="tile__name"><b><font size="2px">'+$("#add_tags :selected").text()+'</b></font> <a id="newCat__'+$("#idx_newsCat").text()+'img" style="text-align: right; float: right;" href="javascript:toggle5(\\'newCat__\\'+$("#idx_newsCat").text()+\\'\\', \\'img\\', \\'newCat__\\'+$("#idx_newsCat").text()+\\'img\\');"><img src= "{% static \\'/img/minus.png\\' %}"></a> </div>' + '<div class="tile__list" id="newCat__'+$("#idx_newsCat").text()+'" style="display: block;"></div>' + '</div>'; $('body').append(template); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 

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