有些情况下需要将 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>