JavaScript 将字符串添加到变量错误

javascript add string to variable error

本文关键字:变量 错误 添加 字符串 JavaScript      更新时间:2023-09-26

我有一个JavaScript程序,直到我试图改变这个:"foldername"这个:http://hokuco.com/test/"+"foldername"+"/index.html"。我的代码有什么问题?对于任何对整个JS感兴趣的人:

     document.getElementById("submit").addEventListener("click", function(){
      var url = document.getElementById("http://hokuco.com/test/"+"foldername"+"/index.html").value;
      window.location.href = "url";
    });
<input type id="foldername"></input>
<input type ="button" id ="submit/>

你可能的意思是:

document.getElementById("submit").addEventListener("click", function(){
  var url = "http://hokuco.com/test/" + document.getElementById("foldername").value + "/index.html";
  window.location.href = url;
});

变化:

  • getElementById函数中的参数与 id 为 "foldername" 的输入元素上的 id 属性相同。
  • window.location.href应设置为变量,而不是带引号的字符串。

更清晰地说,您需要:

document.getElementById("submit").addEventListener("click", function(){
  var folder = document.getElementById("foldername").value;
  var url = "http://hokuco.com/test/" + folder + "/index.html";
  window.location.href = url;
});

现在,希望对正在发生的事情更加清楚。

请阅读以下文档以更好地了解document.getElementById:https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById尝试访问 null 属性时,代码很可能会返回未捕获的类型错误。只能传递引用 Element 对象 ID 的字符串。

你想完成什么?看起来您正在尝试重定向,但使用的是字符串文字而不是变量。