javascript - 如果我的函数评估为 true,如何使我的确认语句发布状态,如果为 false,如何使确认语句发布状态?

标签 javascript if-statement confirm

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

我还尝试创建另一个包含确认语句的“if else”,以返回 true 表示“确定”或返回 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>

预期:按“确定”会发布状态。

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

最佳答案

您必须使用 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>

关于javascript - 如果我的函数评估为 true,如何使我的确认语句发布状态,如果为 false,如何使确认语句发布状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55869355/

相关文章:

javascript - 确认 phantom.js 中的警报窗口

javascript - 在 javascript 中链接回调并保留 'this'

javascript - react : how to pass instance to onClick without using an active index

javascript - "Module not found"自动生成的文件的流程错误

java - 校验值为 'ceiling' 值并返回对应变量

JavaScript:确认对话框显示文本框中的值

javascript - Laravel Dusk Javascript 确认()

javascript - 传递给组件的 Vue Prop 未定义

java - 如果java中的条件!= null,有没有办法再次启动for循环

shell 脚本 : What's the difference between using test and if statement?