我希望当用户单击“提交”时弹出一个确认框,但前提是他们的帖子包含“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/