如果输入值为字符串,则更改窗口位置

时间:2018-09-26 18:48:44

标签: javascript function onclick location window

我正在努力打造一个迷你Google。 在Facebook或Instagram上输入内容的地方,当您单击“搜索”按钮时,您将被转到该页面。 到目前为止,我已经知道了,但这只发给了Facebook。

var btn = document.getElementById("btn");
var search = document.getElementById("search")

btn.onclick = function (){

    if (search.value == "Facebook" || "facebook"){
        window.location = "https://www.facebook.com/";

    } else if( search.value == "Instagram" || "instagram"){
        window.location = "https://www.instagram.com/";
    }
}
<input id="search" type="text"/>
<button id="btn" type="button">Search</button>

1 个答案:

答案 0 :(得分:2)

问题出在您的if上,if (search.value == "Facebook" || "facebook")就像是说

  

如果search.value == "Facebook"为真,或"facebook"为真,请做

这行不通,因为"facebook"始终为真,因此从未输入Instagram的第二个if

相反,您想要的是

  

如果search.value == "Facebook"为真,或者search.value == "facebook"为真,则

var btn = document.getElementById("btn");
var search = document.getElementById("search")

btn.onclick = function (){

    if (search.value == "Facebook" || search.value == "facebook"){
        window.location = "https://www.facebook.com/";

    } else if( search.value == "Instagram" || search.value == "instagram"){
        window.location = "https://www.instagram.com/";
    }
}
<input id="search" type="text"/>
<button id="btn" type="button">Search</button>