gpt4 book ai didi

javascript - 为什么这个 JavaScript 不起作用?

转载 作者:行者123 更新时间:2023-11-28 00:37:36 25 4
gpt4 key购买 nike

这并不应该是安全的,只是为了让不聪明的人远离个人元素。我已经在 HTML 工具包中运行了它并且它运行完美,但是当我在 Web 浏览器中运行它时它不起作用。当我在浏览器中运行它时,它不会重定向到 google.com(只是一个示例),我不确定为什么

<!DOCTYPE html>
<html>
<head>
<script>
var url = "http://www.google.com";
function validateForm() {
var x = document.forms["myForm"]["Uname"].value;
var y = document.forms["myForm"]["Pname"].value;
if (x == "Joshua")
{
if (y == 1234)
{
window.open(url)
}
}
else
{
alert("You have entered the wrong information!");
return false;
}
}
</script>
</head>
<body style="background-color:lightgrey">

<form name="myForm"
onsubmit="return validateForm()" method="post">
Username: <input type="text" name="Uname">
Password: <input type="text" name="Pname">
<input type="submit" value="Submit">
</form>

</body>
</html>

最佳答案

在大多数情况下,您的代码可以正常运行..您只是在“window.open()”后面缺少一个分号..

<小时/>

我选择在submit表单上执行addEventListener;我清理了一些标记。

var url = "http://www.google.com";    

function validateForm(e)
{
var x = document.forms["myForm"]["Uname"].value;
var y = document.forms["myForm"]["Pname"].value;
console.log("%o - %o",document.forms["myForm"]["Uname"].value, document.forms["myForm"]["Pname"].value);
if (x == "Joshua")
{
if (y == 1234)
{
e.target.innerHTML = "<span>SO permission settings don't allow this operation. go to the fiddle to test window.open</span><br /><a href='http://jsfiddle.net/qq7wh80v/1/' target='_blank'>http://jsfiddle.net/qq7wh80v/1/</a>";
//window.open(url);
}
}
else
{
alert("You have entered the wrong information!");

}
return e.returnValue = false;
}

/*
# This next line should run when the dom is ready,
# or when all the resources have been loaded (window.onload || body.onload)

# Note: I'm not doing the onload because it's automatic in this SO 'run code snippet'.
*/

document.getElementById("myForm").addEventListener('submit', validateForm);
<form id="myForm" name="myForm" method="POST">
<label for="Uname">Username</label>:
<input type="text" id="Uname" name="Uname" value="" placeholder="Username" />
<label for="Pname">Password</label>:
<input type="text" id="Pname" name="Pname" value="" placeholder="Password" />
<button type="submit" id="btnSubmit">Submit</button>
</form>

注意:由于沙盒框架上的权限设置,window.open 在此 StackOverflow 代码段中被阻止;因此它不会工作。

Chrome 通知:

"Blocked form submission to 'http://stacksnippets.net/js' because the form's frame is sandboxed and the 'allow-forms' permission is not set."

<小时/>

这是 jsFiddle:http://jsfiddle.net/qq7wh80v/1/

<小时/>

顺便说一句,我在使用 html onEvent 属性时遇到了问题..但这可能是 jsFiddle 问题..

关于javascript - 为什么这个 JavaScript 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28323480/

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