情景是這樣的(小程序或vue下):
優惠活動的詳情頁是通過從數據庫拿到數據動態生成的,數據庫返回的頁面結構數據content:
"<div class='cont-part'><div class='cont-title'></div><div class='cont-image'><img src='http://img.域名隱身之術.cn/524/20191117170216250.png' ></div></div><div class='cont-part'><div class='cont-title'></div><div class='cont-image'><img src='http://img.域名隱身之術.cn/524/20191117170216309.jpg' ></div></div><div class='cont-part'><div class='cont-title'></div><div class='cont-image'><img src='http://img.域名隱身之術.cn/524/20191117170216335.png' ></div></div><div class='cont-part'><div class='cont-title'></div><div class='cont-image'><img src='http://img.域名隱身之術.cn/524/20191117170217306.png' ></div></div>"
結構並不復雜,無非是標題、內容、圖片三個部分,那么如何把這段數據轉義成html顯示在頁面中呢?如下。
首先 在js中封裝好反轉義相關方法:
1 const escapeHtml = str => { // HTML 標簽反轉義 2 var arrEntities = { 3 'lt': '<', 4 'gt': '>', 5 'nbsp': ' ', 6 'amp': '&', 7 'quot': '"', 8 }; 9 return str.replace( /&(lt|gt|nbsp|amp|quot);/ig, function ( all, t ) { 10 return arrEntities[ t ]; 11 } ); 12 } 13 14 const UnicodeToAscii = ( content ) => { // Unicode 轉換 ASCII 15 let contentCopy = content.replace(/&/ig,'&'); 16 let code = contentCopy.match( /&#(\d+);/g ), 17 result = ''; 18 if ( code && code.length > 0 ) { 19 for ( var i = 0; i < code.length; i++ ) { 20 let asciiStr = String.fromCharCode( code[ i ].replace( /[&#;]/g, '' ) ); 21 result = contentCopy.replace( new RegExp( code[ i ], 'g' ), asciiStr ); 22 } 23 return result; 24 } else { 25 return contentCopy; 26 } 27 }
然后 在接口返回數據的地方調用方法:
由於uniapp中不支持div、p、img等標簽,所以要用到replace方法為標簽增加同名類名;
'要替換成單引號 '
1 this.activityBody = res.data.body; 2 this.activityBody.htmlContent = this.tools 3 .UnicodeToAscii(this.tools.escapeHtml(this.activityBody.content)) 4 .replace(/'/gi, "'") 5 .replace(/<p/gi, '<p class="_p"') 6 .replace(/ <img/gi, '<img class="_img"') 7 .replace(/<table/gi, '<table class="_table"');
最后 通過v-html在結構中使用轉義后的content:
1 <div class="content"> 2 <h1> 標題 </h1> 3 <div class="line"><span>我是一條線</span></div> 4 <div v-html="Body.htmlContent"></div> 5 </div>
此處效果自行感受...