我需要使用Javascript window.location.assign()
在输入框中获取用户的输入,一旦单击按钮,该用户将被带到他们在该输入框中输入的URL,我很难在网上找到它。我假设我需要在脚本中添加一个函数(未显示)。
<form style="padding-top: 20px;">
URL: <input type="url" name="url">
<input type="button" value="GO!" onclick="newUrl()">
</form>
答案 0 :(得分:2)
首先,建议不要将功能放在按钮的“ 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);
}
答案 1 :(得分:1)
在使用window.location.assign
之前,我希望您阅读
https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
Location.assign()方法使窗口加载并显示 文档在指定的URL。
如果由于安全违规而无法进行分配,则 抛出SECURITY_ERROR类型的DOMException。如果发生这种情况 调用该方法的脚本的原点与原点不同 最初由Location对象描述的页面的 该脚本托管在其他域中。
如果提供的URL无效,则为SYNTAX_ERROR的DOMException 类型被抛出。
在这里您可以使用它
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>