Javascript 如果代码正确,单击重定向按钮
我正在尝试设置它,以便有两个按钮。“签出”按钮和“带代码签出”按钮。如果您点击“签出”按钮,您将被重定向到一个页面。我做到了,一点问题也没有 对于“使用代码签出”按钮,如果代码正确,您将被重定向到其他页面。如果代码错误,将出现警报并显示“无效代码”。如果代码正确,我不知道如何让按钮将您重定向到第二页 这是我的代码:Javascript 如果代码正确,单击重定向按钮,javascript,html,redirect,Javascript,Html,Redirect,我正在尝试设置它,以便有两个按钮。“签出”按钮和“带代码签出”按钮。如果您点击“签出”按钮,您将被重定向到一个页面。我做到了,一点问题也没有 对于“使用代码签出”按钮,如果代码正确,您将被重定向到其他页面。如果代码错误,将出现警报并显示“无效代码”。如果代码正确,我不知道如何让按钮将您重定向到第二页 这是我的代码: <!DOCTYPE html> <script type='text/javascript'> //this is the code that is
<!DOCTYPE html>
<script type='text/javascript'>
//this is the code that is used to checkout, when you press the checkout with code button.
var code = 123456
//if code is right, redirect to page2
function checkOut2 () {
if (code = 123456) {window.location.pathname = "nintendo.com"} else {
alert("Invalid Code");
}
}
</script>
<html>
<body>
<button type="button" onclick="location.href = 'www.yoursite1.com'" id="checkOut">Checkout</button>
<br>
<br>
<button type="button" id="checkOut2">Checkout With Code</button>
<br>
Code:
<input type="text" name="code">
<br>
</body>
</html>
//当您按下“使用代码签出”按钮时,这是用于签出的代码。
var代码=123456
//如果代码正确,请重定向到第2页
函数签出2(){
如果(code=123456){window.location.pathname=“nintendo.com”}else{
警报(“无效代码”);
}
}
结账
用代码签出
代码:
所以,当你按下“用代码签出”按钮,在“代码”文本框中有一个有效的代码时,你会被重定向到任天堂网站。但是我不知道如何使其正常工作。首先,修复用于将
=
与=
进行比较的运算符
function checkOut2 () {
if (code == 123456) {window.location.pathname = "nintendo.com"} else {
alert("Invalid Code");
}
}
然后尝试将函数附加为事件侦听器:
var button = document.getElementById('checkOut2');
button.addEventListener("click", checkOut2);
此外,要从输入中检索代码,请首先添加id属性:
<input type="text" id="code"/>
您应该真正阅读一些Javascript教程,这是一件简单的事情
function checkOut2() {
var code = document.getElementById("code").value;
if(code == "123456"){
window.location = "nintendo.com"
} else {
alert("Invalid Code");
}
}
<input type="text" id="code">
<button type="button" id="checkOut2" onclick="checkOut2();">Checkout With Code</button>
函数签出2(){
var代码=document.getElementById(“代码”).value;
如果(代码==“123456”){
window.location=“nintendo.com”
}否则{
警报(“无效代码”);
}
}
用代码签出
=
是赋值运算符,而不是比较运算符。如果JavaScript是客户端的,我建议不要在客户端检查代码,因为它在源代码中或多或少可见。(请注意,您可以检查md5或类似的东西,但这仍然不是一个好主意。)要获得有效的HTML,请单击按钮
,那么为什么不使用表单上的操作
属性转到您想去的地方呢?将id更改为name。您将一个名为的输入更改为id为的输入。因此,现在一切正常。这对我来说非常有效,非常感谢!不客气!
function checkOut2() {
var code = document.getElementById("code").value;
if(code == "123456"){
window.location = "nintendo.com"
} else {
alert("Invalid Code");
}
}
<input type="text" id="code">
<button type="button" id="checkOut2" onclick="checkOut2();">Checkout With Code</button>