如果我的函数评估为true,我如何使我的确认声明发布状态,如果为false则取消?

问题描述 投票:2回答:1

我希望在用户点击提交时弹出确认框,但前提是他们的帖子包含“sale”和“£”等字符串。不幸的是,无论是否单击“确定”或“取消”,代码都会转发到操作页面。

我还尝试创建另一个包含confirm语句的'if else',返回true为Ok或False为Cancel,但无效。

对不起,如果其中一些很难理解,我是一个菜鸟,并试图围绕JavaScript。

<script>
function check() {

 var post = document.forms["myForm"]["newPost"].value;
    if (post.indexOf('sale') > -1 || post.indexOf('£') > -1) {
     confirm("If this is a 'for sale' post, please post to the marketplace instead. Press OK to post as a general status."); 
 }
}
</script>

<form name="myForm" action="/post-page.php" onSubmit="return check()" method="post">
Post: <input name="newPost" id="newPost">
  <input type="submit" value="Post Now">
</form>

预期:按OK即可发布状态。

结果:两个选项都发布状态。

javascript if-statement confirm
1个回答
3
投票

您必须使用confirm()的返回值来控制事件的流程:

function check() {

 var post = document.forms["myForm"]["newPost"].value;
    if (post.indexOf('sale') > -1 || post.indexOf('£') > -1) {
     var res = confirm("If this is a 'for sale' post, please post to the marketplace instead. Press OK to post as a general status."); 
     if(res) return true;
     else return false;
 }
}
<form name="myForm" action="/post-page.php" onSubmit="return check()" method="post">
Post: <input name="newPost" id="newPost">
  <input type="submit" value="Post Now">
</form>
© www.soinside.com 2019 - 2024. All rights reserved.