【问题标题】:How can I make my confirm statement post a status if my function evaluates as true, or cancel if false?如果我的函数评估为真,我如何让我的确认声明发布状态,或者如果为假,则取消?
【发布时间】:2019-04-26 14:06:25
【问题描述】:

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

我还尝试创建另一个包含确认语句的“if else”,为 Ok 返回 true 或为 Cancel 返回 False,但无济于事。

抱歉,如果其中一些内容难以理解,我是菜鸟,我正试图将我的头脑围绕在 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】:

    你必须使用confirm()return值来控制事件的流程:

    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>

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2020-10-07
    • 1970-01-01
    相关资源
    最近更新 更多