html - 如何在javascript中单击按钮时从一个html页面重定向到另一个页面?
问题描述
我有两个html页面page_1.html
和page_2.html
. 在page_1.html
中,我有一个按钮,单击该按钮后应重定向到page_2.html
. 但仅当按钮具有黄褐色背景色时,它才应重定向。
所以,在 中page_1.html
,我有一个按钮:
Organization:<div id="org"><input type="checkbox" id="cb1" >ID no: <input type="number" id="org_number" style="visibility: hidden"><br><br>
<input type="checkbox" id="cb2" >Mobile No: <input type="tel" id="ph_number" style="visibility: hidden" required></div><br><br>
<button id="button" onmouseover="hovar()" onclick="submit()" >Register</button>
<script src="back_end.js" async></script>
我的 javascript (back_end.js):
function hovar(){
var phone=document.getElementById("ph_number").value;
var btn=document.getElementById("button");
if (phone.length!=10){
btn.style.backgroundColor="lightsalmon"
}
else{
btn.style.backgroundColor="chartreuse"
btn.style.color="black"
}
}
function submit(){
var btn=document.getElementById("button");
if (getComputedStyle(btn).backgroundColor == "charteuse"){
window.location.href="page_2.html";
}
}
但是,它不会重定向到page_2.html
. 我在这里想念什么?我也试过window.location.replace("page_2.html")
,但都是一样的。
编辑:我已经稍微更改了代码,它来自我正在做的一个项目。我也尝试过getComputedStyle(document.getElementById("button")).backgroundColor
,但它不起作用。
我注意到的另一件事是,当我使用:
if (btn.style.backgroundColor == "charteuse"){
//console.log(true)
location.href="page_2.html";
}
它打印true
到控制台,但仍然没有重定向到page_2.html
.
但如果我使用:
if (getComputedStyle(btn).backgroundColor == "charteuse"){
//console.log(true)
window.location.href="page_2.html";
}
它不会打印true
到控制台中。但是,在这两种情况下,它都不会重定向到page_2.html
解决方案
ElementCSSInlineStyle.style
style 属性用于获取和设置元素的内联样式。获取时,它会返回一个 CSSStyleDeclaration 对象,该对象包含该元素的所有样式属性的列表,以及为元素的内联样式属性中定义的属性分配的值。
https://developer.mozilla.org/en-US/docs/Web/API/ElementCSSInlineStyle/style
因此,您的 if-conditondocument.getElementById("button").style.backgoundColor == "red"
永远不会返回 true,因为颜色是在您的css-file
而不是作为内联参数中定义的。
一种解决方案是使用getComputedStyle(element)
从css-file
.
getComputedStyle(document.getElementById("button")).backgroundColor == "red"
如此处所述https://zellwk.com/blog/css-values-in-js/
同样在您的css
,您可以删除"red"
@George 提到的引号
推荐阅读
- c# - 后跟空双括号的 `is` 运算符是什么?
- java - 无法调用 JTable,因为 tableDisplay 为空
- javascript - 如何在猫鼬的对象数组中搜索对象?
- python - 为什么 python telethon 在与电报连接时给出信号量错误
- firebase - 我们如何为 Firebase 存储编写依赖于 Firebase 实时数据库中的值的安全规则?
- opencl - 是否所有与 OpenCL 优化相关的选项都默认为 false?
- python - 如何在保留 \n 的同时拆分字符串
- botframework - 在 Adaptive Cards ActionSet 和 markdown 列表中使用自动换行
- android - android 导航 popBackStack 行为
- python - Python 3.9 MetaClass 属性与 Classmethod 属性