Use confirm() as a condition to if?

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

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?

回答1:

When you compare a return value to true you shouldn't use return true, just 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:

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:

function RemoveProduct() {   return confirm("Poista?"); } 

Remember to use return when you use the function in an event. Example:

<input type="submit" onclick="return RemoveProduct();" /> 


回答2:

confirm() returns a boolean value and you can return that. Like so:

function RemoveProduct() {     return confirm("Poista?"); } 


回答3:

But as far as I know, I can't use another brackets on the if sentence conditions?

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.

Here is your code greatly simplified.

var confirmed = confirm('whatever'); return confirmed; 


回答4:

just use

<a onclick="return confirm('ARe sure want to remove');">remove</a> 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!