Multiple buttons with the same #id to do the same function?

时间:2022-09-03 16:51:03

JS beginner, sorry

JS初学者,对不起

How can could I make it so that every button that has the id "#popit" to open the same popup box?

我怎么能这样做,以便每个具有id“#popit”的按钮打开相同的弹出框?

I'm using bPopup

我正在使用bPopup

With this code there is only one button on the site which does open the popup

使用此代码,网站上只有一个按钮可以打开弹出窗口

;(function($) {
    $(function() {
        $('#my-button').bind('click', function(e) {
            e.preventDefault();
            $('#element_to_pop_up').bPopup();
        });
    });
})(jQuery);

http://jsfiddle.net/yg5so25s/ - there are 3 buttons with the same id, but only the first one opens the popup box, anyway I could make it so that every single button to open the same popupbox?

http://jsfiddle.net/yg5so25s/ - 有3个按钮具有相同的ID,但只有第一个按钮打开弹出框,无论如何我可以让它每个按钮打开相同的弹出框?

2 个解决方案

#1


9  

id must be unique, you need to use class instead:

id必须是唯一的,你需要使用class:

<button class="my-button">POP IT UP</button>

then you can use . to target elements by class name:

那你可以用。按类名定位元素:

;(function($) {
    $(function() {
        $('.my-button').bind('click', function(e) {
            e.preventDefault();
            $('#element_to_pop_up').bPopup();
        });
    });
})(jQuery);

Updated Fiddle

更新小提琴

#2


2  

use common class for all buttons

对所有按钮使用通用类

$('.commonClass').bind('click', function(e) {
            e.preventDefault();
            $('#element_to_pop_up').bPopup();
        });

DEMO

DEMO

#1


9  

id must be unique, you need to use class instead:

id必须是唯一的,你需要使用class:

<button class="my-button">POP IT UP</button>

then you can use . to target elements by class name:

那你可以用。按类名定位元素:

;(function($) {
    $(function() {
        $('.my-button').bind('click', function(e) {
            e.preventDefault();
            $('#element_to_pop_up').bPopup();
        });
    });
})(jQuery);

Updated Fiddle

更新小提琴

#2


2  

use common class for all buttons

对所有按钮使用通用类

$('.commonClass').bind('click', function(e) {
            e.preventDefault();
            $('#element_to_pop_up').bPopup();
        });

DEMO

DEMO