call the same jQuery function in multiple buttons

后端 未结 10 2121
星月不相逢
星月不相逢 2020-12-01 11:12

I am not really familiar with jQuery. I have this code that I downloaded to create a fade in/fade out popup form. Here\'s the code:



        
相关标签:
10条回答
  • 2020-12-01 11:31

    Create an array for unique buttonid dynamically in the loop like

    $button[] = '#'.$buttonid; 
    

    Outside the loop use implode to convert this array to comma separated string

    $jsstring = implode(",",$button);
    

    Now use php to pass above string as selector in your js code like:

    $(document).ready(function() {
        $('< php echo $jsstring ; ?>').click(function(){ });
    });
    
    0 讨论(0)
  • 2020-12-01 11:39

    you class can call them by class you using , seperated id

    $(document).ready(function() {
    $('#button, #button1, #button2').click(function(e) { 
    $('#modal').reveal({ 
    animation: 'fade',
    animationspeed: 150,
    closeonbackgroundclick: true, 
    dismissmodalclass: 'close'
    });
    return false;
    });
    });​
    
    0 讨论(0)
  • 2020-12-01 11:40

    First solution :

    function doClick(e) { 
       $('#modal').reveal({ 
         animation: 'fade',
         animationspeed: 150,
         closeonbackgroundclick: true, 
         dismissmodalclass: 'close'
       });
       return false;
    }
    $('#button1').click(doClick);
    $('#button2').click(doClick);
    

    Second solution :

    Give a class "someClass" to all the involved buttons

    <input type=button class=someClass ...
    

    and do

    $('.someClass').click(function(e) { 
    ...
    });
    

    Third solution :

    Use the comma to separate ids :

    $('#button1, #button2').click(function(e) { 
    ...
    });
    

    Generally, the best solution is the second one : it allows you to add buttons in your code without modifying the javascript part. If you add some of those buttons dynamically, you may even do

    $(document).on('click', '.someClass', function(e) { 
    ...
    });
    
    0 讨论(0)
  • 2020-12-01 11:42

    If you use same buttonid for all button then there is no need to call all buttons..just simply use this code..It seems that you are using animation in this code....well use togglefade instead of reveal

    <script type=text/javascript> $(document).ready(function(){ $("button").click(function(){ $("#buttonid").fadein(); $("#buttonid").fadeout(); }); }); </script>

    0 讨论(0)
提交回复
热议问题