如何使用视窗位置

时间:2019-04-17 21:23:47

标签: javascript html dom

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

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>

3 个答案:

答案 0 :(得分:0)

使用window.open

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

答案 1 :(得分: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>

在我的代码段中,我正在传递ID为url的输入元素的值

答案 2 :(得分: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>