简体   繁体   English

一种功能-许多按钮

[英]One function - many buttons

I have in HTML a button with id="button1". 我在HTML中有一个id =“ button1”的按钮。

We have JavaScript function: 我们有JavaScript函数:

$('#button1').click(function() { ... } );

It works well. 它运作良好。

But what if we have 100 buttons with different IDs? 但是,如果我们有100个具有不同ID的按钮怎么办?

I can duplicate 100x function. 我可以复制100x函数。 However, this is not very elegant and good solution. 但是,这不是很好的解决方案。

How to easily and effectively solve a problem for many buttons? 如何轻松有效地解决许多按钮的问题?

The function performed is the same for all buttons. 所有按钮执行的功能均相同。

Add a class bind to this: 添加一个与此绑定的类:

 $(document).ready(function(){ //dot (.) selector binds to classes $('.boundButton').click(function(){ //clicked button var $this = $(this); alert($this.attr('id')); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="1" class="boundButton">1</button> <button id="2" class="boundButton">2</button> <button id="3" class="boundButton">3</button> 

You need to use a class instead of ID. 您需要使用类而不是ID。 For example, your JS code could look like: 例如,您的JS代码如下所示:

$('.button-class').click(function() { ... } );

and your HTML might look like 并且您的HTML可能看起来像

<button name='example' class='button-class' id='exampleID'>Button Text</button>

Here is the basic example: 这是基本示例:

 $(document).ready(function () { $(".btn").on("click", function(){ //attach click event to all buttons with class "btn" console.log($(this).attr("id")); //$(this) refers to the button clicked }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="btn1" class="btn">Button 1</button> <button id="btn2" class="btn">Button 2</button> <button id="btn3" class="btn">Button 3</button> 

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

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