简体   繁体   English

无法转到JavaScript中的网址

[英]Can't go to a url in javascript

I am a total noob to web programming (Started just now). 我完全不喜欢Web编程(刚刚开始)。 I know C, C++ and x86-assenbly (a little bit). 我知道C,C ++和x86-assenbly(一点点)。 I wanna create my own home page for my browser. 我想为浏览器创建自己的主页。 It's very basic html for the most part but I want a search bar on the top that redirects to duckduckgo with relevant results and that's where the problem arises. 在大多数情况下,这是非常基本的html,但我想在顶部找到一个搜索栏,将其重定向到具有相关结果的duckduckgo,这就是问题所在。 The code I'm trying: 我正在尝试的代码:

<form>
    <input type="text" id="query"/>
    <button id="button" class="button" onclick="openInDuck()">Search</button>
</form>
<script>
    function openInDuck(){
        var x= "https://duckduckgo.com/?q=";
        x += document.getElementById("query").value;
        window.location = x;
    }
</script>

And yeah, I forgot, I am using qutebrowser on archlinux if that matters. 是的,我忘记了,如果那很重要,我会在archlinux上使用qutebrowser。 Thanks in advance. 提前致谢。

You are missing .href on your redirect. 您在重定向中缺少.href Also you should change the button type to button instead of the default; 同样,您应该将按钮类型更改为button而不是默认值。

 function openInDuck() { var x = "https://duckduckgo.com/?q="; x += document.getElementById("query").value; window.location.href = x; } 
 <form> <input type="text" id="query" /> <button id="button" class="button" onclick="openInDuck()" type="button">Search</button> </form> 

Do note that it wouldn't be ideal to redirect the user if you just need to do a search through a different api. 请注意,如果您只需要通过其他api进行搜索,则重定向用户不是理想的选择。

You can use the below 您可以使用以下

function openInDuck()    {
    var    x="https://duckduckgo.com/?q=";
    x    +=    document.getElementById("query").value;
    window.open(x);
}

Problem is that your form is submitted when clicking the button, like this it works :) 问题是单击该按钮时提交了您的表单,就像这样:)

<input type="text" id="query" /> 
<button id="button" class="button" onclick="openInDuck()">Search</button>

<script>
    function openInDuck() {
        var x = "https://duckduckgo.com/?q=";
        x += document.getElementById("query").value;
        window.location = x;
    }
</script>

You are close to the solution. 您已接近解决方案。 In the JS code, you must add .href after window.location to set the new href (URL) for the current window. 在JS代码中,必须在window.location之后添加.href才能为当前窗口设置新的href(URL)。 In the HTML code, I suggest you use the onsubmit attribute to send the form with an input type="submit" : 在HTML代码中,建议您使用onsubmit属性发送input type="submit"的表单:

 function openInDuck() { var x = "https://duckduckgo.com/?q="; x += document.getElementById('query').value; window.location.href = x; return false; // Prevent the form submission } 
 <form onsubmit="return openInDuck()"> <input type="text" id="query"> <input type="submit" id="button" class="button" value="Search"> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM