JavaScript 抛出错误 "Uncaught TypeError: Cannot set property ' value' of null"yet element is present

标签 javascript html jsp tomcat jspx

我正在研究 jsp。我有一个 <input> jsp 文件中的元素。但是当我尝试设置 <input id="digipan" name="digipan" type="hidden" value="" ></input> 的值时使用 javascript 我收到此错误:“未捕获的类型错误:无法设置 null 的属性‘值’”。 这是我的 html 代码:

<div class="col-xs-12 contactDetails">
        <div class="col-md-6">
           <mark>PAN Card</mark>
            <div >
               <label style="color: red">Choose File:</label> 
               <div class="form-group">
                 <input type='file' id="PAN_Card" name="PAN_Card" /> <div id="dl_pan"> OR <div class="share_fm_dl" id="attachment_poi" ></div></div>
               </div>
               <div id="digipanfile" name="digipanfile"></div>
               <input id="digipan" name="digipan" type="hidden" value="" ></input>
             </div>
       </div>
    </div>

这是我的 Javascript 代码:

document.getElementById('digipanfile').innerHTML = "File:<a href=" + response + ">" + filename + "</a>";
        document.getElementById('digipan').value = response;
        document.getElementById('PAN_Card').style.display = 'none';

此 javascript 代码位于仅在页面加载后执行的函数内。 此外,查看页面源显示此 <input>标签,但 Inspect Element 没有显示它。 注意:- 我已经在使用 jQuery 文档就绪方法,但仍然出现此错误。

最佳答案

您必须等到文档加载完毕。所以你应该在你的javascript文件中使用“加载”事件监听器:

window.addEventListener("load", e => {
        document.getElementById('digipanfile').innerHTML = "File:<a href=" + response + ">" + filename + "</a>";
        document.getElementById('digipan').value = response;
        document.getElementById('PAN_Card').style.display = 'none';
    })

您还可以使用 jQuery 方法窗口加载和文档就绪。两者大致同时发生。如果您想知道其中哪一个先触发,您应该运行此代码以了解:

$(document).ready(function() {
      alert("document ready occurred!");
});

$(window).load(function() {
      alert("window load occurred!");
});

关于JavaScript 抛出错误 "Uncaught TypeError: Cannot set property ' value' of null"yet element is present,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49271847/

相关文章:

javascript - 自定义指令 : How evaluate bindings with dynamic HTML

javascript - 将数组解密为字符串

javascript - 隐藏屏幕阅读器中的所有元素(一格除外)?

java - 如何在 Apache tomcat 服务器启动时自动定期运行我的 java 函数?

java - 数据库负载均衡

javascript - 使用 node.js 驱动程序强制执行特定的 MongoDB 模式

javascript - Ajax 表行需要身份验证

html - div位置后自动高度

jquery - 查找文本中的所有实例并全部替换

java - JSTL - 比较字符串