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:27

Another alternative, assuming your elements are stored as variables (which is often a good idea if you're accessing them multiple times in a function body):

function disableMinHeight() {
    var $html = $("html");
    var $body = $("body");
    var $slideout = $("#slideout");

    $html.add($body).add($slideout).css("min-height", 0);
};

Takes advantage of jQuery chaining and allows you to use references.

查看更多
弹指情弦暗扣
3楼-- · 2019-01-02 17:27

Add a comma separated list of classes like this :

jQuery(document).ready(function($) {

$('.class, .id').click(function() { 

//  Your code

    }

});
查看更多
无与为乐者.
4楼-- · 2019-01-02 17:27

In addition to the excellent examples and answers above, you can also do a "find" for two different elements using their classes. For example:

<div class="parent">
<div class="child1">Hello</div>
<div class="child2">World</div>
</div>

<script>
var x = jQuery('.parent').find('.child1, .child2').text();
console.log(x);
</script>

This should output "HelloWorld".

查看更多
登录 后发表回答