Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

javascript - call the same jQuery function in multiple buttons

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:

<script type='text/javascript'>
    $(document).ready(function() {
        $('#button').click(function(e) { 
            $('#modal').reveal({ 
                animation: 'fade',
                animationspeed: 150,
                closeonbackgroundclick: true, 
                dismissmodalclass: 'close'
            });
            return false;
        });
    });
</script>

The code above executes when a button with an id='button' is clicked. Now I have multiple buttons, how can I call this function in all buttons? I tried setting the id of all buttons to button but only the first button works. Any help would be very much appreciated. By the way I forgot to mention, in my .php file i have this codes:

for ($c=1;$c<=5;$c++){
echo "<input type='button' id='button'">
};

This php code will display 5 buttons with the same id which is 'button'. What I want to happen is when I click any of the 5 buttons the jQuery function will execute which is popping up a fade in/fade out form.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) { 
...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...