【问题标题】:"get ElementById" not working on firefox?“getElementById”不能在 Firefox 上运行?
【发布时间】:2021-07-23 10:00:44
【问题描述】:

我可以从文件上传到 IE 和 Chrome 的 textarea 中获取文件名。 但是在firefox上不行,我该如何解决这个问题?

非常感谢。

        function takeName(event) {
            let filename = event.path[0].files[0].name;
            document.getElementById("txtComment").value = filename;
        }
  
<form id="Apply" name="Apply" method="post" enctype="multipart/form-data" action="applyLeave.php">
    Get upload filename to textarea:
    <p><textarea rows="3" cols="30" name="txtComment" id="txtComment" class="valid"></textarea></p>
    <p>Select image to upload: <input type="file" onchange="takeName(event)" name="fileToUpload" id="fileToUpload"></p>
    <p><input type="submit" value="Submit" name="submit"></p>
</form>

【问题讨论】:

  • 有什么问题?你怎么知道它在 Firefox 上不起作用?
  • 好吧,我使用 Firefox 和 document.getElementById 发布的作品很好。
  • 您的代码混合了多种可能性,因此第 1 步是将其拆分。 let element = event.path[0]; let file = element.files[0]; let name = file.name; let comment = document.getElementById("txtComment"); comment.value = filename; 然后你会首先注意到你想要event.target,而不是event.path[0],然后你会注意到这与document.getElementById 无关,并且你跳到结论而不是验证你的假设。在调试时获得额外的详细信息总是好的。一旦一切正常,您随时可以再次折叠它。

标签: javascript html


【解决方案1】:

document.getElementById() 与任何浏览器的兼容性是毫无疑问的,这不是问题。请参阅此 answer 关于 .path 与 Firefox 的兼容性。

event.path[0] 替换为event.target

function takeName(event) {
  let filename = event.target.files[0].name;
  document.getElementById("txtComment").value = filename;
}
<form id="Apply" name="Apply" method="post" enctype="multipart/form-data" action="applyLeave.php">
  Get upload filename to textarea:
  <p><textarea rows="3" cols="30" name="txtComment" id="txtComment" class="valid"></textarea></p>
  <p>Select image to upload: <input type="file" onchange="takeName(event)" name="fileToUpload" id="fileToUpload"></p>
  <p><input type="submit" value="Submit" name="submit"></p>
</form>

【讨论】:

    【解决方案2】:

    当我在显示event.path is undefined的firefox中使用时,我建议你使用event.target.files来获取文件名

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 2021-05-07
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多