0

我在使用 JavaScript 时遇到了一些问题。我的问题是我有一个用户输入框(用户将在其中输入 URL)和一个按钮(单击时,它将打开用户在输入框中键入的 URL)。

这是我的代码:

<input type="text" id="userurlbox"/>
<button type="button" onClick="myFunction()">Open URL</button>

<script>
function myFunction()
{
var x = document.getElementById('userurlbox').value;
if (x == "")
{
alert('Please enter a URL');
}

else
{
window.open(x ,'_blank');
}
</script>

问题是 URL 像这样打开:

http://mywebsite.com/USERURL

我希望它像这样打开:

http://USERURL
4

3 回答 3

0

我刚刚测试过,需要 'http://'在window.open中包含

<input type="text" id="userurlbox"/>
<button type="button" onClick="myFunction()">Open URL</button>

<script>
function myFunction(){
var x = document.getElementById('userurlbox').value;

    x = x.replace('http://'.''); // remove  http:// just in-case it is there

    if (x == "")
    {
        alert('Please enter a URL');
    }    
     else
    {
       window.open('http://' + x ,'_blank');
    }
}

</script> 
于 2013-05-22T10:15:47.467 回答
0

如果尚未包含此代码,则仅添加“http://”:

function myFunction() {
        var x = document.getElementById('userurlbox').value; 
        if (x == "") {
            alert('Please enter a URL');
        }
        else {
            if (x.substr(0,4).toLowerCase() === 'http') { // only test first 4 characters as we want to allow both http:// and https://
                window.open(x ,'_blank');
            }
            else {
                window.open('http://'+x);
            }
        }
    }
于 2013-05-22T10:17:47.177 回答
-1

我不确定您是否可以仅使用 window.open 函数覆盖相对/绝对 url 行为,因此一个可行的解决方案是检查 url 是否以 https?:// 开头,如果是,则在前面加上 '//'不是。以 // 开头的 URL 将始终被视为绝对 URL。

于 2013-05-22T10:18:40.287 回答