Reducing duplicated code with JQuery function

前端 未结 2 1649
梦毁少年i
梦毁少年i 2021-01-13 18:03

Found a good jquery popup function here:

 JAVASCRIPT
 $(function() {
    $(\"#word1234\").live(\'click\', function(event) {
        $(this).addClass(\"selec         


        
相关标签:
2条回答
  • 2021-01-13 18:13

    Don't use live use on, live was deprecated as of 1.7:

    You could give your links a popup class and do:

    $(".popup").on("click", function() {
        // Your code
    }); 
    

    That way you can capture all links with the popup class and are not binding to 100's of events, i.e:

    $("#id1").click() { }
    $("#id2").click() { }
    

    etc.

    0 讨论(0)
  • 2021-01-13 18:23

    You could turn the code into a jQuery Plugin like this:

    $.fn.myPopup = function(popupText){
        var popupHtml = '<div class="messagepop pop">' + popupText + '</div>';
        this.each(function(){
            $(this).click(function(){
    
                // Create the popup
                $(this).addClass("selected").parent().append(popupHtml);
    
                // Find the close button and attach click handler
                $(this).find(".close").click(
                    // Find, hide, then delete the popup
                    $(this).closest(".pop").slideFadeToggle().remove();;
                );
    
            });
            return false;
        });
    
        return this;
    };
    

    Then your code would look like this:

    $("#word1234").myPopup("Lorem Ipsum");
    $("#wordABCD").myPopup("Hello World");
    
    0 讨论(0)
提交回复
热议问题