简体   繁体   English

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

[英]How do you select more than one element by id?

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! 谢谢!

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

http://docs.jquery.com/Selectors

You can use 您可以使用

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

Or 要么

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

Both methods are good 两种方法都很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM