有些情況下需要將 HTML 元素中包含的 HTML 標簽去除。
代碼如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>jQuery如何從元素中除去HTML標簽</title> <link rel="stylesheet" type="text/css" href="../css/demos.css"/> <style type="text/css"> </style> </head> <body> <h2 id="h2-caption">jQuery如何從元素中除去HTML標簽</h2> <input type="button" id="id-button-striphtmltag" value="從元素中除去HTML標簽"/><br> <div id="div-striphtmltag"> <p> <table border="1" style="padding:2px;"> <tr> <td>1</td> <td>jQuery</td> <td>如何從元素中除去HTML標簽</td> </tr> <tr> <td>2</td> <td>jQuery</td> <td>如何從元素中除去HTML標簽</td> </tr> <tr> <td>3</td> <td>jQuery</td> <td>如何從元素中除去HTML標簽</td> </tr> </table> </p> </div> <script src="../../js/jquery-1.9.1.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> // 除去HTML標簽 ;(function( $ ){ $.fn.stripHtmlTag = function(){ // 使用正則進行匹配 var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi; this.each(function(){ $(this).html($(this).html().replace(regexp,'')); }); return $(this); } })( jQuery ); $(function(){ $('#id-button-striphtmltag').click(function(){ $('#div-striphtmltag').stripHtmlTag(); }); }); </script> </body> </html>