将文本框中输入的文字追加到url并打开url链接

将文本框中输入的文字追加到url并打开url链接

问题描述:

我有以下代码:

<script type="text/javascript">
function changeText2(){
    var userInput = document.getElementById('userInput').value;
    var lnk = document.getElementById('lnk');
    lnk.href = "www.google.com/search/" + userInput;
    lnk.innerHTML = lnk.href;
}


</script>

Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' value=' ' />
<input type='button' onclick='changeText2()' value='Change Link'/>

因此,这基本上执行以下操作:

So, this basically does the following:

用户在文本框中输入一个词,该词会附加在给定链接 (www.google.com/search/) 的末尾.并且链接显示在页面上方.

User enters a word in the text box, and that word is appended at the end of the link given (www.google.com/search/). And the link is displayed above on the page.

但不是在页面上显示链接,我希望它在单击按钮时打开该页面.我该怎么做?

But instead of displaying the link on the page, I want it to open that page when the button is clicked. How can I do that?

见这个fiddleH2>

尝试 window.location 在点击时重定向到页面.

See this fiddle

Try window.location to redirect to the page on click.

也就是说,在你的代码中尝试

That is, in your code try like

<script type="text/javascript">
function changeText2(){
    var userInput = document.getElementById('userInput').value;
    var lnk = document.getElementById('lnk');
    lnk.href = "www.google.com/search/" + userInput;
    window.location = "www.google.com/search/" + userInput;
}
</script>