我试图在条件语句失败后返回 false。
我有
$('#btn').click(function() {
$('.title').each(function() {
if (id == $(this).attr('id')) {
alert('The name already exists.')
return false; //I hope my codes would stop here if condition is true
}
})
// my codes still call the doSomething function even if the conditional
//statement is true
doSomething();
})
我只想在 id != $(this).attr('id).
时调用 doSomething
函数
下面的代码给了我想要的东西,但看起来很难看。
$('#btn').click(function() {
var nameExist = false
$('.title').each(function() {
if (id == $(this).attr('id')) {
alert('The name already exists.')
nameExist = true;
return false; //I hope my codes would stop here if condition is true
}
})
if (!nameExist) {
doSomething();
}
})
有人对此有更好的方法吗?非常感谢!
最佳答案
切换到基本的 for 循环。
$('#btn').click(function() {
var elements = $(".title");
for (var i = 0; i < elements.length; i++) {
if (id == elements[i].id) {
alert('The name already exists.')
return false; //I hope my codes would stop here if condition is true
}
}
doSomething();
})
关于javascript - 如何改进我的代码以实现 'return false'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13940618/