JavaScript:文本元素返回 "undefined"

JavaScript: text element returning "undefined"

我正在尝试通过 ID 标签查询和循环来检索每个文本框中输入的文本。

但是当我打印检索到的内容时,它会输出 "undefined"。

看起来你的 post 主要是代码:

</head>
  <body bgcolor="#E6E6FA">
    <font color=black size=+3>Modifying Sentiment</font>
    <table>
      <tr>
        <td>Text to Save:</td>
      </tr>
      <tr>
        <td colspan="3">
          Add positive adjective:
          <img Adjective src="http://findicons.com/files/icons/2776/android_icons/96/ic_question_mark.png" alt="question" title="Adjective: is a word naming an attribute of a noun, such as sweet, red, or technical."
            width=20 />
          <br>
          <textarea cols=40 rows=3 id="textbox" ></textarea>
          <textarea id="textbox" style="width:512px;height:256px"></textarea>
        </td>
      </tr>
      <tr>
        <td>Filename to Save As:</td>
        <td><input id="inputFileNameToSaveAs"></input></td>
        <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
      </tr>
      <tr>
        <td>Select a File to Load:</td>
        <td><input type="file" id="fileToLoad"></td>
        <td><button onclick="loadFileAsText()">Load Selected File</button>
        <td>
      </tr>
    </table>
    <script type='text/javascript'>
      function saveTextAsFile(){
        var textBoxes = document.querySelectorAll('textbox');
        var textToWrite;
        for(var i in textBoxes){
          textToWrite = textBoxes[i].value;
          window.alert(textToWrite);
        }
        var textToWrite = document.getElementById("textbox").value;
        var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
        var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
      }
    </script>

实际上 html 文档中的每个 id 值都应该是唯一的。在您的 HTML 代码中,我可以看到两个具有相同值 "textbox" 的 id 参数。尝试将第一个更改为 "textbox-1" 或任何对您有意义的值,但不要为 id 属性 重复相同的值,它应该可以工作。

我已将您的 javascript 编辑为指向 textarea 而不是 textbox。 我还修改了你的 for 循环,因为我在控制台中获得了额外的输出。我还将您的 alert 更改为 console.log,因为 jsbin 抛出了可能无限循环的错误。 试试这个:

function saveTextAsFile()
{
    var textBoxes = document.querySelectorAll('textarea');
    var textToWrite;
    for(var i = 0; i < textBoxes.length; ++i){
      textToWrite = textBoxes[i].value;
      console.log(textToWrite);
    }


    textToWrite = document.getElementById("textarea").value;

    var textFileAsBlob = new Blob([textToWrite],{type:'text/plain'});

    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
}

尝试使用 #textbox,因为它指的是 dom 元素的 ID