jQuery - 從元素中去除 HTML 標簽


有些情況下需要將 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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM