我正在尝试找出一种在单击不同按钮时返回不同结果的方法。我有两个按钮,它们根据用户单击的内容返回值。这是一个与我的代码很接近的代码。
$(() => {
const $btn1 = $("#btn1"),
$btn2 = $("#btn2");
let result = 0;
function fetchResult() {
if("button1 is clicked"){ //Of course, that isn't the condition being tested
result = 1 + 2;
} else if ("button2 is clicked") { //And neither is this
result = 3 + 4;
} else {
//do nothing
}
return result;
}
$("#result").html(fetchResult);
});
#result {
text-align: center;
font-size: 30px;
background: green;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div>
<button class="btn btn-lg" id="btn1">Button 1</button>
<button class="btn btn-lg" id="btn2">Button 2</button>
<p id="result"></p>
</div>
最佳答案
您必须添加一个事件监听器来处理点击事件才能使其工作:
$btn1.on('click', function() {
console.log('button 1 clicked');
});
$btn2.on('click', function() {
console.log('button 2 clicked');
});
或者您可以将事件添加到 .btn
类中,并根据元素的 id 确定单击的是哪一个:
$('.btn').on('click', function() {
if (this.id === 'btn1') {
console.log('button 1 clicked');
} else if (this.id === 'btn2') {
console.log('button 2 clicked');
}
});
后一种方法可能更适合您的特定用例。
关于javascript - 如何获取条件(If/Else)来检查按钮是否被单击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42936535/