如何使用窗口位置

问题描述 投票:-1回答:3

所以我想创建一个带有文本框和按钮的表单,单击该按钮打开我在文本框中键入的URL,有关如何使用函数使其工作的任何建议?

function open(url) {
  var win = window.location(url, '_blank');
  win.focus();
}
<form>
  Give Url:<br>
  <input type="url" name="url" placeholder="http://www.example.com"><br>
</form>
<button type="button" onclick="open(url)">Open Url</button>
javascript html dom
3个回答
0
投票

使用window.open

function open(url) {
    var win = window.open(url, "_blank");
    win.focus();
}

0
投票

问题是你传入了一个名为url的未知变量:

function open(url) {
  var win = window.location(url, '_blank');
  win.focus();
}
<form>
  Give Url:<br>
  <input id="url" type="url" name="url" placeholder="http://www.example.com"><br>
</form>
<button type="button" onclick="open(document.getElementById('url').value)">Open Url</button>

在我的片段中,我传递的输入元素的值为url


0
投票

您没有在任何地方提交任何表单数据,因此您不需要form元素,并且您的input不需要name属性。

只需要打电话给window.open(url)you should not be setting up your event handlers in HTML(即使你看到其他人都这样做了)。

下面的代码有效,但在Stack Overflow代码片段环境中没有。 But, you can test the same code here.

let tb = document.querySelector("input"); // Get a reference to the textbox

// Get a reference to the button and set up the click event handler for it
document.querySelector("button").addEventListener("click", function () {
  var win = window.open(tb.value);
});
Give Url:<br>
<input type="url" placeholder="http://www.example.com"><br>
<button type="button">Open Url</button>
© www.soinside.com 2019 - 2024. All rights reserved.