在多个按钮中调用相同的jQuery函数 [英] call the same jQuery function in multiple buttons
问题描述
我对jQuery并不熟悉。我有我下载的代码来创建淡入/淡出弹出窗体。以下是代码:
< script type ='text / javascript'>
$(document).ready(function(){
$('#button')。click(function(e){
$('#modal')。reveal({
动画:'fade',
animationspeed:150,
closeonbackgroundclick:true,
dismissmodalclass:'close'
});
返回false;
});
});
< / script>
上面的代码在 id ='button'
被点击。现在我有多个按钮,如何在所有按钮中调用此功能?我尝试将所有按钮的 id
设置为按钮
,但只有第一个按钮有效。任何帮助将非常感激。
顺便说一句,我忘了提及,在我的.php文件中我有这个代码:
$ $ $ $ $ $ $ $ $ = 1; $ c< = 5; $ c ++){
echo< input type ='button'id ='button'>
};
这个php代码会显示5个按钮,它们是'button'。我想要发生的事情是,当我点击jQuery函数执行的5个按钮中的任何一个时,它会弹出一个淡入/淡出形式。
函数doClick(e){
$('#modal')。reveal({
animation:'fade',
animationspeed:150,
closeonbackgroundclick:true,
dismissmodalclass:'close'
});
返回false;
}
$('#button1')。click(doClick);
$('#button2')。click(doClick);
第二种解决方案:
$ b $给所有相关的按钮赋予一个类someClass。
< input type = button class = someClass .. 。
和做
($ e $ {
});
第三种解决方案:
使用逗号分隔ID:
$('#button1,#button2')。click(function( e){
...
});
通常,最好的解决方案是第二个:它允许你在你的代码中添加按钮而不用修改javascript部分。如果您动态添加其中一些按钮,您甚至可以执行
$(document).on('click',')。 someClass',函数(e){
...
});
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.
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) {
...
});
这篇关于在多个按钮中调用相同的jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!