Javascript 使用confirm() 作为if 的条件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12073352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use confirm() as a condition to if?
提问by Guffa
I have this function:
我有这个功能:
function RemoveProduct() {
if (confirm("Poista?") == return true) {
return true;
} else {
return false;
}
}
When you click a "remove" button on the page, it should ask if it should remove a product, and if the answer is yes, it will remove it.
当您单击页面上的“删除”按钮时,它应该询问是否应该删除产品,如果答案是肯定的,它将删除它。
But as far as I know, I can't use another brackets on the if sentence conditions? How this should be done?
但据我所知,我不能在 if 语句条件上使用另一个括号?这应该怎么做?
回答by Guffa
When you compare a return value to true
you shouldn't use return true
, just true
:
当您将返回值与true
您不应该使用的值进行比较时return true
,只需true
:
function RemoveProduct() {
if (confirm("Poista?") == true) {
return true;
} else {
return false;
}
}
You don't even need to do the comparison, as the result from confirm
is a boolean value:
您甚至不需要进行比较,因为结果confirm
是一个布尔值:
function RemoveProduct() {
if (confirm("Poista?")) {
return true;
} else {
return false;
}
}
And you don't even need the if
statement, you can just return the result from confirm
:
而且您甚至不需要该if
语句,您只需从confirm
以下位置返回结果:
function RemoveProduct() {
return confirm("Poista?");
}
Remember to use return
when you use the function in an event. Example:
请记住return
在事件中使用该函数时使用。例子:
<input type="submit" onclick="return RemoveProduct();" />
回答by hvgotcodes
But as far as I know, I can't use another brackets on the if sentence conditions?
但据我所知,我不能在 if 语句条件上使用另一个括号?
There is nothing that prevents you from executing a function within an if condition. That said, I always get all the arguments to my conditional settled before the if, for clarity and readability.
没有什么可以阻止您在 if 条件内执行函数。也就是说,为了清晰和可读性,我总是在 if 之前解决我的条件的所有参数。
Here is your code greatly simplified.
这是您的代码大大简化。
var confirmed = confirm('whatever');
return confirmed;
回答by Per Salbark
confirm()
returns a boolean value and you can return that. Like so:
confirm()
返回一个布尔值,你可以返回它。像这样:
function RemoveProduct() {
return confirm("Poista?");
}
回答by Govind Malviya
just use
只是使用
<a onclick="return confirm('ARe sure want to remove');">remove</a>