你如何通过id选择多个元素?

时间:2021-03-16 21:05:55

I have two identical click events for two different elements that do not share a class, as such:

对于两个不共享类的不同元素,我有两个相同的点击事件,如下所示:

$("#element_1").click(function(){
  alert("hello world");
});

$("#element_2").click(function(){
  alert("hello world");
});

I am looking for a way to assign that same click function to both of them without externalizing the function or repeating it (as seen above). If the elements shared the same class, I would have done something like this:

我正在寻找一种方法来为这两个函数分配相同的点击功能,而无需外化函数或重复它(如上所示)。如果元素共享同一个类,我会做这样的事情:

$(".element_class").click(function(){
  alert("hello world");
});

but they do not. How do I achieve something like that in jQuery 1.3?

但他们没有。如何在jQuery 1.3中实现类似的功能?

Thank you!

2 个解决方案

#1


$('#element_1, #element_2').bind('click', function() {...});

http://docs.jquery.com/Selectors

#2


You can use

您可以使用

$('#element1, #element2').click();

Or

$('#element1').add('#element2').click();

Both methods are good

两种方法都很好

#1


$('#element_1, #element_2').bind('click', function() {...});

http://docs.jquery.com/Selectors

#2


You can use

您可以使用

$('#element1, #element2').click();

Or

$('#element1').add('#element2').click();

Both methods are good

两种方法都很好