Reducing duplicated code with JQuery function

前端 未结 2 1648
梦毁少年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:23

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

    $.fn.myPopup = function(popupText){
        var popupHtml = '
    ' + popupText + '
    '; 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");
    

提交回复
热议问题