Home  >  Article  >  Web Front-end  >  Can jquery bind events to multiple elements at the same time?

Can jquery bind events to multiple elements at the same time?

WBOY
WBOYOriginal
2022-04-26 17:31:262573browse

jquery can bind events to multiple elements together. Binding method: When using a selector to select elements, separate the element selectors with commas to bind events to multiple elements together, and support the mixed use of multiple selectors. The syntax is "$(element 1, Element 2, Element 3...).Event (event handler function)".

Can jquery bind events to multiple elements at the same time?

The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.

Can jquery bind events to multiple elements at the same time?

During the development process, I have encountered binding the same event to each row or column in the table. The method used is jquery. Traverse the column elements and use foreach to bind events to each cell. What we are going to talk about today is the binding method of interactively triggering the same click event on different elements.

The specific method is as follows:

$("#id1, .class1, #id2, .class2").unbind("click").click(function(){
    console.log("test");
})

When using selectors to select elements, use English commas to separate them. At the same time, mixed use of selectors is supported, so that the same event can be bound to different elements.

The example is as follows:

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $(".bt1,#bt1").click(function(){
    $("p").slideToggle();
  });
});
</script>
</head>
<body>
<p>这是一个段落。</p>
<button class="bt1">切换</button>
<button id="bt1">切换</button>
</body>
</html>

Output result:

Can jquery bind events to multiple elements at the same time?

##Related video tutorial recommendation:

jQuery video tutorial

The above is the detailed content of Can jquery bind events to multiple elements at the same time?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn