简体   繁体   中英

Selective Rendering of Plain HTML Tag

Please consider the code below.

Here are what I need to happen:

1.) The html tag from variable msg_raw will be rendered as plain html.

2.) The html tag from variable message will be applied, which would mean that the output display will have a red colored ABC text and blue colored <b>DEF</b> text, like so:

ABC           <-- red colored text
<b>DEF</b>    <-- blue colored text

 var msg_raw = '<b>DEF</b>'; var message = '<div class="red_text">ABC</div>'; message += '<div class="blue_text">' + msg_raw + '</div>'; $('#some_ID').html(message);
 .red_text{ color: red; } .blue_text{ color: blue; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="some_ID"></div>

After inserting the <b> as HTML, insert the text that needs to be inside it with .text :

 var msg_1 = '<span class="red_text">ABC</span>'; $('#some_ID').html('<b/>'); $('#some_ID > b').text(msg_1);
 .red_text{ color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="some_ID"></div>

For a more dynamic option, you can replace all characters with a special meaning in HTML with their HTML entity in the msg_raw before concatenating it into message :

 // https://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript var encodedStr = rawStr => rawStr.replace(/[\ -\香<>\\&]/gim, function(i) { return '&#'+i.charCodeAt(0)+';'; }); var msg_raw = '<b>DEF</b>'; var message = '<div class="red_text">ABC</div>'; message += '<div class="blue_text">' + encodedStr(msg_raw) + '</div>'; $('#some_ID').html(message);
 .red_text{ color: red; } .blue_text{ color: blue; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="some_ID"></div>

you can also use < and > instead < and > :

 var msg_1 = '&lt span class="red_text"&gtABC &lt/span&gt'; var msg_2 = '<b>' + msg_1 + '</b>'; $('#some_ID').html(msg_2);
 .red_text{ color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="some_ID"></div>

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