douqiao6015 2015-05-21 18:08
浏览 32

是否有一个TypeError:变量在JavaScript中是否为空?

I've got an HTML form that when submitted uses PHP to dynamically build another form. The first form action uses $_SERVER['PHP_SELF'] so the second form is on the same page. The second form action is handed off and processed by a FPDF and PHP page and ultimately outputs a PDF.

JavaScript is used on the second form to dynamically build and show additional sections of the form based on input choices made on the sections of the second form as it progresses.

In my JavaScript, I have some variables I setup for ease of use that reference several areas of the second form. My JavaScript does have a window.onload function and my issue does not occur because the DOM isn't loaded before my JavaScript.

Because I dynamically build the 2nd form after the initial page load and after the first form is submitted I see this error in my Console:

TypeError: myVariable is null.

// Examples of myVariable which are HTML elements not present 
// in the DOM until the first form has been submitted.

var drawingsWrapper = document.getElementById('drawingsWrapper');
var groupClass = drawingsWrapper.getElementsByClassName('group');
var groupClassLength = groupClass.length;

Once the second form is built, this error goes away as the HTML element it references is now on the page. Everything is working as expected with my forms and processing, including the JavaScript.

As I am not yet an expert on JavaScript I am making myself use it and know it very well before I start relying on a library like jQuery and I am really working hard at understanding the little nuances.

Question: Is this error acceptable given that it is thrown because the element it is referencing is not yet present in the DOM or is there something I should be doing to not declare the variable until the portion of the DOM it references it is present?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
    • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
    • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
    • ¥15 如何在炒股软件中,爬到我想看的日k线
    • ¥15 seatunnel 怎么配置Elasticsearch
    • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
    • ¥15 (标签-MATLAB|关键词-多址)
    • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
    • ¥500 52810做蓝牙接受端
    • ¥15 基于PLC的三轴机械手程序