首页 > 解决方案 > 如何在javascript中单击按钮时从一个html页面重定向到另一个页面?

问题描述

我有两个html页面page_1.htmlpage_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

标签: 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 提到的引号


推荐阅读