我正在创建一个站点并有一个文本字段,您可以在其中输入文本,它会将自己 append 到 url。现在我的系统可以正常工作,但是不会显示页面。
这是我的代码:
<script>
function changeText2() {
var userInput = document.getElementById('userInput').value;
var lnk = document.getElementById('lnk');
lnk.href = "http://jwallach.prepdev.org/" + userInput;
window.location = "http://jwallach.prepdev.org/" + userInput;
}
</script>
Link <a href="" id=lnk>nothing </a>
<br>
<input type='text' id='userInput' value=' ' />
<input type='button' onclick='changeText2()' value='Change Link' />
但是,由于网址前面有%20,无法找到该页面。我该如何解决这个问题? Site
最佳答案
要么从输入中删除前导空格:
<input type='text' id='userInput'/>
...或 trim 内容:
function changeText2(){
var userInput = document.getElementById('userInput').value.trim();
var lnk = document.getElementById('lnk');
lnk.href = "http://jwallach.prepdev.org/" + userInput;
window.location = "http://jwallach.prepdev.org/" + userInput;
}
后者是一个更好的主意,因为前导/尾随空格是用户在字段中键入/粘贴时常犯的错误。
如果用户没有故意输入 URL 的一部分,您还应该确保对他们的输入进行URL 编码,以防他们的输入包含非 URL 安全字符:
lnk.href = "http://jwallach.prepdev.org/" + encodeURIComponent(userInput);
关于javascript - 将用户文本输入添加到 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48123635/