我有一个按钮,上面有两个点击事件。 我想做的是根据某个条件阻止该按钮上的两个或所有事件。
我尝试使用 event.preventDefault();
和 event.stopPropagation();
和 return false;
但没有任何效果,因为我需要。
/* I need to stop $('button') event if the if condition
inside $('#btn') event passed */
$('#btn').click(function(e){
var term = $('#term').val();
if(term != '') {
//e.preventDefault();
//e.stopPropagation();
return false;
alert(2);
} else {
// continue
}
});
$('button').click(function(e){
alert(1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="term" type="text" placeholder="type here ..">
<button type="button" id="btn">Check</button>
最佳答案
要突破您的函数,请仅使用 return;
(而不是 return false;
)
此外,您无法在返回
后设置任何代码,因此您可以:
$('#btn').click(function(e){
e.preventDefault();
var term = $.trim( $('#term').val() );
if(term !== "") {
alert("Value exists! I'm breaking any further operations.");
return; // "Exit" my function
// YOU CANNOT WRITE CODE AFTER A RETURN STATEMENT!
} else { // Else is actually not needed but it's cool to have it for clearance
alert("Value is empty.");
}
});
$('button').click(function(e){
alert(1); // You'll see this in any case.
});
<小时/>
扩展您的问题如何防止弹出警报(1)
$('#btn').click(function(e){
e.preventDefault();
this.term = $.trim( $('#term').val() );
if(this.term) {
alert("Value exists!");
} else {
alert("Value is empty.");
}
});
$('button').click(function(e){
if(!this.term) {
alert(1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="term" type="text" placeholder="type here ..">
<button type="button" id="btn">Check</button>
关于javascript - 停止同一按钮上的一个点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36114202/