JavaScript引发错误“未捕获的TypeError:无法将属性'value'设置为null"元素仍然存在 [英] JavaScript is throwing error "Uncaught TypeError: Cannot set property 'value' of null" yet element is present

查看:124
本文介绍了JavaScript引发错误“未捕获的TypeError:无法将属性'value'设置为null"元素仍然存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on on jsp. I have an <input> element in jsp file. But when I am tring to set value of <input id="digipan" name="digipan" type="hidden" value="" ></input> using javascript I am getting this error: "Uncaught TypeError: Cannot set property 'value' of null". This is my html code:

<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代码:

And this is my Javascript code:

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

此javascript代码位于一个函数内,该函数仅在页面加载后才执行. 另外,查看页面源"显示此<input>标记,但检查元素"未显示该标记. 注意:-我已经在使用jQuery文档就绪方法,但是仍然出现此错误.

This javascript code is inside a function which is executed only after page load. Also, View Page Source is showing this <input> tag but Inspect Element is not showing it. Note:- I am already using jQuery document ready method but still having this error.

推荐答案

您必须等待文档加载完毕.因此,您应该在JavaScript文件中使用加载"事件监听器:

You have to wait till the document is loaded. So you should use the "load" eventlistener in your javascript file:

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方法窗口加载并准备好文档.两者大致同时发生.如果您想知道哪个首先触发,则应运行以下代码以了解:

You could also use the jQuery methods window load and document ready. Both occur roughly at the same time. If you want to know which one of them fires first you should run this code to know:

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

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

这篇关于JavaScript引发错误“未捕获的TypeError:无法将属性'value'设置为null"元素仍然存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆