Javascript 基于值的按钮重定向响应
我正在根据文本字段中给定的值编写url方向代码。如果username和password中的值为test,则应指向页面。如果输入了其他值,则应在同一页上显示错误消息Javascript 基于值的按钮重定向响应,javascript,html,css,Javascript,Html,Css,我正在根据文本字段中给定的值编写url方向代码。如果username和password中的值为test,则应指向页面。如果输入了其他值,则应在同一页上显示错误消息 <label for="uname">Username:</label> <input type="text" id="uname" name="uname" value=""> <br>
<label for="uname">Username:</label>
<input type="text" id="uname" name="uname" value=""> <br>
<label for="pwd">Password:</label><br>
<input type="text" id="pwd" name="pwd" value=""><br>
<button class="login" onsubmit="redirectPage()">Login</button>
<script>
function redirectPage(uname,pwd)
{
if (uname == 'test' and pwd=='test')
{window.location = "http://www.google.com";}
else
document.write("The code is wrong, try again!")
}
</script>
用户名:
密码:
登录
功能重定向页面(uname,pwd)
{
如果(uname=='test'和pwd=='test')
{window.location=”http://www.google.com";}
其他的
编写(“代码错误,请重试!”)
}
我知道代码是非常错误的,但我正在尝试学习一些新的东西。您需要引用该字段,因为变量不是作为参数传输的
<script>
function redirectPage() {
if (document.getElementById('uname').value == 'test' && document.getElementById('pwd').value == 'test') {
window.location = "http://www.google.com";
} else {
document.write("The code is wrong, try again!")
}
}
</script>
函数重定向页面(){
if(document.getElementById('uname')。value='test'&&document.getElementById('pwd')。value='test'){
window.location=”http://www.google.com";
}否则{
编写(“代码错误,请重试!”)
}
}
函数重定向页面(){
var uname=document.getElementById('uname').value;
var pwd=document.getElementById('pwd')。值
如果(uname=='test'&&pwd=='test'){
window.location=”https://www.google.com";
}否则{
编写(“代码错误,请重试!”)
}
}
用户名:
密码:
您需要获取uname
和pwd
的值,然后调用重定向页面函数
功能重定向页面(uname,pwd){
如果(uname==“测试”&&pwd==“测试”){
window.location.href=”https://www.google.com";
}否则{
编写(“代码错误,请重试!”);
}
}
document.querySelector(“#handleOnSubmit”).addEventListener(“单击”,“事件)=>{
event.preventDefault();
const uname=document.querySelector(“#uname”).value;
const pwd=document.querySelector(“#pwd”).value;
重定向页面(uname,pwd);
});代码>
用户名:
密码:
登录
您可以使用如下所述的javascript:
函数ValidateUser(){
if(document.getElementById(“uname”).value='test'&&document.getElementById(“pwd”).value='test'){
窗口打开(“https://www.google.com");
}否则{
document.write(“代码错误,请重试”)
}
}
HTML格式为:
用户名:
密码:
登录
或者,您可以使用jQuery
实现以下两个代码段的相同功能:
函数ValidateUser(){
如果($(“#uname”).val()='test'&&$(“#pwd”).val()='test'){
窗口打开(“https://www.google.com");
}否则{
document.write(“代码错误,请重试”)
}
}
或:
$(文档).ready(函数(){
$(“#btnLogin”)。单击(函数(){
如果($(“#uname”).val()='test'&&$(“#pwd”).val()='test'){
窗口打开(“https://www.google.com");
}否则{
document.write(“代码错误,请重试”)
}
})
});
HTML中有一点变化:
用户名:
密码:
登录
我希望这只是为了测试和学习,而不是您尝试使用的真正密码访问。别忘了客户端的JS不是一个安全的地方。哦,是的,这只是为了了解这个功能是如何工作的!我试图设计一个虚拟网站,让我的团队学习自动化测试。。