gpt4 book ai didi

javascript - 禁用来自外部 Javascript 的表单操作字段

转载 作者:行者123 更新时间:2023-12-03 10:05:36 24 4
gpt4 key购买 nike

我有一个带有 action="result.php 的 html 表单。现在的问题是,我希望我的表单仅在我的 javascript 中的某些函数返回 true 并且我有这个来实现这一点时才继续到 result.php

function init() {
var form1 = document.getElementById("test");
if (validat() == true){
form1.onsubmit = validatequiz;
}
}

window.onload = init;

validat 函数返回 truefalse,因此在上面的函数中我检查其返回值并执行 onsubmit ,但即使我的 validate() 函数返回的值是 false,我仍然会被重定向到 result.php,这是我不想做的。

问题是,操作是在 html 文件内设置的,我正在检查外部 javascript 文件中的表单,我不允许在 html 文件中使用内部 javascript,这就是我遇到此问题的原因。

最佳答案

您的 JavaScript 不会执行任何操作来阻止提交操作完成。要停止提交表单,您需要使用

在 Javascript 中显式停止它
return false;

event.preventDefault();

Question: How do I prevent the browser's default action in a JavaScript event handler?

Answer: In the early days of JavaScript, to prevent the default response to an event, you could simply refurn false from the respective event handler. For example, returning false from an onsubmit event handler would prevent the browser from submitting the form; returning false from the onclick event handler of a link would prevent the browser from following the link. In most modern browsers, behavior like the above still works; however, now there are many more supported event types, and the actual behavior may depend on the browser and the event type.

关于javascript - 禁用来自外部 Javascript 的表单操作字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30372056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com