1.index.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Extension example of jQuery plug-in</title>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>  </head>
<body>

<p>Xu Tongbao</p>

<script>
    // Closures qualify namespaces
    (function ($) {
        // Default parameters
        var defaluts = {
            foreground: 'red'.background: 'yellow'
        };
        $.fn.extend({
            "highLight": function (options) {
                // Check whether the parameters passed in by the user are valid
                if(! isValid(options)) {return this;
                }
                // Override the plugin default parameters with jquery.extend
                var opts = $.extend({}, defaluts, options);
                // This is the jQuery object. Return is used to support chained calls
                // Iterate over all the DOM to highLight when a collection is called with the highLight() plugin.
                return this.each(function () {
                    // Get the jQuery object of the current DOM, where this is the dom of the current loop
                    var $this = $(this);
                    // Style the DOM according to the parameters
                    $this.css({
                        backgroundColor: opts.background,
                        color: opts.foreground
                    });
                    // Format highlighted text
                    varmarkup = $this.html(); markup = $.fn.highLight.format(markup); $this.html(markup); }); }});// Public formatting methods. The default is bold, and users can override this method to achieve different formatting effects.
        $.fn.highLight.format = function (str) {
            return "<strong>" + str + "</strong>";
        };
        // Private method to check whether the parameter is valid
        function isValid(options) {
            return! options || (options &&typeof options === "object")?true : false;
        }
    })(window.jQuery);

    / / call
    // The caller overrides the public method exposed by the plug-in
    $.fn.highLight.format = function (txt) {
        return "<em>" + txt + "</em>"
    };

    $(function () {$("p").highLight({ foreground: 'orange'.background: '#ccc' }); // Call the custom highlighting plug-in
    });
</script>
</body>
</html>
Copy the code

\

2. Run result \

\