无法前往 javascript 中的 url

Can't go to a url in javascript

我完全是网络编程的菜鸟(刚刚开始)。我知道 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,才能为当前的window设置新的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>