如何获取用户输入的值以对其进行href处理?

时间:2018-09-20 18:51:44

标签: javascript html html5

我想获取输入的值以使其成为HREF,例如,用户输入为192.168.1.1,我想在单击按钮时重定向到该输入,因此我可以直接转到该IP地址是我的代码:

function displayCam()
{
    var ip = document.getElementById('ipadd');
    document.getElementById('camView').innerHTML = ip.value;
}
<h1>Input IP Address</h1>
<label for="ipadd">Enter IP Address:</label>
<input type='text' id='ipadd' />
<input type='button' onclick='displayCam()' value='Submit' />   
<div id="camView"> </div>

3 个答案:

答案 0 :(得分:2)

使用isArchived

答案 1 :(得分:2)

要重定向到他们添加的IP地址,您可以将displayCam修改如下:

function displayCam()
{
    var ip = document.getElementById('ipadd');
    document.getElementById('camView').innerHTML = ip.value;
    if (ip.value.indexOf('://') === -1) {
        ip.value = "http://" + ip.value; // Use http by default
    }
    window.location.href = ip.value;
}

答案 2 :(得分:0)

您可以这样做:

div 内放置 anchor 标记,并在按钮单击时动态设置 href

<script>
function displayCam()
{
    var ip = document.getElementById('ipadd');
    document.getElementById('camView').innerHTML = ip.value;
    document.getElementById('camView').href="http://"+ip.value;

    //Or to open in new tab on submit button directly 
    var url="http://"+ip.value;
    window.open(url)
}
</script>

<h1>Input IP Address</h1>
<label for="ipadd">Enter IP Address:</label>
    <input type='text' id='ipadd' />
    <input type='button' onclick='displayCam()' value='Submit' />

<div><a href="" id="camView" target="_blank" ></a></div>