繁体   English   中英

无法转到JavaScript中的网址

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

我完全不喜欢Web编程(刚刚开始)。 我知道C,C ++和x86-assenbly(一点点)。 我想为浏览器创建自己的主页。 在大多数情况下,这是非常基本的html,但我想在顶部找到一个搜索栏,将其重定向到具有相关结果的duckduckgo,这就是问题所在。 我正在尝试的代码:

<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>

是的,我忘记了,如果那很重要,我会在archlinux上使用qutebrowser。 提前致谢。

您在重定向中缺少.href 同样,您应该将按钮类型更改为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> 

请注意,如果您只需要通过其他api进行搜索,则重定向用户不是理想的选择。

您可以使用以下

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

问题是单击该按钮时提交了您的表单,就像这样:)

<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>

您已接近解决方案。 在JS代码中,必须在window.location之后添加.href才能为当前窗口设置新的href(URL)。 在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