jQuery same click event for multiple elements

2019-01-02 16:30发布

Is there any way to execute same code for different elements on the page?

$('.class1').click(function() {
   some_function();
});

$('.class2').click(function() {
   some_function();
});

instead to do something like:

$('.class1').$('.class2').click(function() {
   some_function();
});

Thanks

标签: jquery events
9条回答
深知你不懂我心
2楼-- · 2019-01-02 17:12
$('.class1, .class2').click(some_function);

Make sure you put a space like $('.class1,space here.class2') else it wont work

查看更多
十年一品温如言
3楼-- · 2019-01-02 17:16

We can code like following also, I have used blur event here.

$("#proprice, #proqty").blur(function(){
      var price=$("#proprice").val();
      var qty=$("#proqty").val();
      if(price != '' || qty != '')
      {
          $("#totalprice").val(qty*price);
      }
  });
查看更多
长期被迫恋爱
4楼-- · 2019-01-02 17:20

Simply use $('.myclass1, .myclass2, .myclass3') for multiple selectors. Also, you dont need lambda functions to bind an existing function to the click event.

查看更多
深知你不懂我心
5楼-- · 2019-01-02 17:21

I have a link to an object containig many input fields, which requires to be handled by the same event. So I simply use find() to get all the inside objects, that need to have the event

var form = $('<form></form>');
// ... apending several input fields

form.find('input').on('change', onInputChange);

In case your objects are one level down the link children() instead find() method can be used.

查看更多
残风、尘缘若梦
6楼-- · 2019-01-02 17:23
$('.class1, .class2').on('click', some_function);

Or:

$('.class1').add('.class2').on('click', some_function);
查看更多
流年柔荑漫光年
7楼-- · 2019-01-02 17:25

I normally use on instead of click. It allow me to add more events listeners to a specific function.

$(document).on("click touchend", ".class1, .class2, .class3", function () {
     //do stuff
});

Hope it helps!

查看更多
登录 后发表回答