javascript - 将用户文本输入添加到 url

标签 javascript html css append

我正在创建一个站点并有一个文本字段,您可以在其中输入文本,它会将自己 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/

相关文章:

javascript - 编辑使用 leaflet.shapefile 上传的 shapefile

android - 表格不适合移动设备上的父容器大小

CSS变换函数顺序

html - 避免 IE8 复选框的 css hack

javascript - 在 uiwebview ios 中采购本地 javascript

javascript - System.Data.Entity.DynamicProxies foreach

html - 处理html和css中的链接

jquery - 使用 Jquery 根据 td 值更改行颜色

php - 在 PHP 中设置 Iframe 样式

javascript - React JS npm start 显示无法编译 web-vitals