所以我想创建一个带有文本框和按钮的表单,单击该按钮打开我在文本框中键入的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>
使用window.open
:
function open(url) {
var win = window.open(url, "_blank");
win.focus();
}
问题是你传入了一个名为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
您没有在任何地方提交任何表单数据,因此您不需要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>