I am new in javascript. How to use single event handler for four buttons. Both html and js should be in single page. Thanks in advance.
<html>
<head>
<script>
myFunc() {
var fired_button = $(this).val(); alert(fired_button);
}
</script>
</head>
<body>
<input type="button" value="one" onClick="myFunc()"><br>
<input type="button" value="two" onClick="myFunc()"><br>
<input type="button" value="three" onClick="myFunc()"><br>
<input type="button" value="four" onClick="myFunc()"><br>
</body>
</html>
Since you are using jquery
, you don't need the onclick
attribute, just add a class that is similar for all buttons. And DO NOT forget to add the js
file of jquery
above all js
files
$('.someClass').click(function() {
alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="someClass" type="button" value="one"><br>
<input class="someClass" type="button" value="two"><br>
<input class="someClass" type="button" value="three"><br>
<input class="someClass" type="button" value="four"><br>
来源:https://stackoverflow.com/questions/46762571/single-event-handler-for-four-button-clicks