For example, I have several buttons, in one of them, by pressing, I write the execution of some actions, for example, display the text of the button in the label. It is necessary that by pressing another button the exact same action was done as by pressing the first button. I will not copy all the code manually ... I think that you can somehow trigger the action in the second button from the first? Tell me how to do it.
2 answers
For languages with OOP can be different. For example:
- Create a method that performs the actions that should occur on pressing. Assign a click listener to each button and call this method there.
- Create a separate class that implements the button click listener interface. Pass the instance to the listener assignment method.
- If the listener is assigned to all buttons in one class, then make this class implement the listener interface and send this class to the listener’s assignee, i.e.
this
- oneIt seems to me that he will not master your answer. Judging by the question, he is a beginner and if he understood what you were writing about, he would not ask such questions. - XelaNimed
- oneThe first point is clear to me, I will try. Thank you;) - Tim Leyden
- My example is certainly not with just two buttons, a little more difficult (I try to remake the notebook), but with your help I figured out one of the questions :) Thank you very much everyone! - Tim Leyden
|
Sketched an example.
Here we add an event handler to all elements with the class of buttons in the div , and to those that are present, and to those that appear later.
If your buttons are not added dynamically, then the string$("div").on("click", ".buttons", function(e) { ... });
must be replaced by$("div .buttons").on("click", function(e) { ... });
$("#container").on("click", ".buttons", function(e) { $("textarea").append($.trim($(e.target).text()) + ", "); }); $("#addButton").on("click", function(e) { var num = $("#container .buttons").length + 1; var $button = $("#container .buttons:first").clone().html("Button " + num).appendTo("div"); }); div, p { margin: 5px; } textarea { width: 100%; height: 50px; margin: 0; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <button class="buttons">Button 1</button> <button class="buttons">Button 2</button> <button class="buttons">Button 3</button> </div> <p> <button id="addButton">Add button</button> </p> <textarea></textarea> - A good example, but a question, like, for Java) - Yuriy SPb ♦
- @ YurySPb I screwed up this :( - XelaNimed
- And right now, with a light movement, we will turn a mistake into ... not a mistake. Watch for question marks) - Yuriy Spb ♦
|