window.location.assign() 导航到 url 的用户输入?

window.location.assign() navigate to user input of url?

我需要使用 Javascript window.location.assign() 从输入框中获取用户的输入,单击按钮后,用户将被带到他们输入的 URL输入框-我很难在网上找到这个。我假设我需要向我的脚本添加一个函数(未显示)。

    <form style="padding-top: 20px;">
        URL: <input type="url" name="url">
        <input type="button" value="GO!" onclick="newUrl()">
    </form>

在使用 window.location.assign 之前,我希望您阅读这篇文章

https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

The Location.assign() method causes the window to load and display the document at the URL specified.

If the assignment can't happen because of a security violation, a DOMException of the SECURITY_ERROR type is thrown. This happens if the origin of the script calling the method is different from the origin of the page originally described by the Location object, mostly when the script is hosted on a different domain.

If the provided URL is not valid, a DOMException of the SYNTAX_ERROR type is thrown.

这是您可以使用它做什么

function newUrl(){
  window.location.assign(document.getElementById("url").value);
}
 <form style="padding-top: 20px;">
        URL: <input type="url" name="url" id="url">
        <input type="button" value="GO!" onclick="newUrl()">
    </form>

首先,我建议不要将 "onclick" 中的函数放在按钮中,而是将其放在表单元素的 "onsubmit" 处理程序中。这样,一个简单的 "Enter" 键也可以引起导航。

其次,由于我们将回调放在表单上,​​因此表单的操作应更改为 'javascript',如下所示:

<form style="padding-top 20px;" action="javascript://#" onsubmit="newUrl(this.elements['url'].value)">
    URL: <input type="text" name="url">
    <input type="submit" value="GO!">
</form>

我把url放在了"newUrl"函数的第一个参数里,为了写的方便。

最后,您的 "newUrl" 函数:

function newUrl(url) {
    window.location.assign(url);
}

简单的选择

<form style="padding-top 20px;" onsubmit="this.action=document.getElementById('url').value">
  URL: <input type="text" id="url">
  <input type="submit" value="GO!">
</form>