我正在研究 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/