Как вставить информацию, собранную по подсказкам в нескольких различных функциях, для отображения в элементе Div в JavaScript? - PullRequest
0 голосов
/ 19 апреля 2019

Я пытаюсь собрать информацию от пользователя с помощью подсказок, каждая из которых имеет свои собственные функции.Каждая из этих функций работает сама по себе, как я их проверил.Затем я пытаюсь отобразить информацию в Div с помощью функции financialInfoDisplay (), но получаю следующее сообщение об ошибке

Uncaught TypeError: Невозможно установить свойство 'innerHTML' для null в financialInfoDisplay

и запросы не отображаются в браузере.Почему это и как я могу это исправить?

Я даже пытался включить код для добавления .innerHTML в div в каждой функции, что работает, но как только я добавляю еще одно приглашение в div, первое исчезает.

Я даже пытался добавить параметры вместо глобальных переменных, таких как var userWithdrawal, userName, depositAmount, в financialInfoDisplay (), а затем передать эти переменные в качестве аргументов при вызове указанной функции, но это тоже не сработало.

//GLOBAL VARIABLES
var userWithdrawal, userName, depositAmount;

//GETS ELEMENT FROM DOM
var $ = function (id) {
    "use strict";
    return window.document.getElementById(id); 
};
//GETS USER NAME 
function namePrompt () {
    "use strict";
    userName = window.prompt("Please enter your name");
    return userName;
}

//GETS DEPOSIT AMOUNT
function depositAmountPrompt () {
    "use strict";
    depositAmount = window.prompt("Please enter the amount of money you would like to deposit");
    return depositAmount;
    
}
//GETS WITHDRAWAL Amount
function withdrawalAmount () {
    "use strict";
     userWithdrawal = window.prompt("Please enter the amount of money you would like to withdrawal from your account");
     return userWithdrawal;
}

//DISPLAYS THE PROMPTS WITHIN A DIV
function financialInfoDisplay() {
    "use strict";
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML = userName + depositAmount + userWithdrawal;
    return infoDisplay;
}

financialInfoDisplay();

//HANDLES ALL EVENT LISTENERS
function init() {
    "use strict";
    $('nameBtn').addEventListener("click", namePrompt);
    $('depositBtn').addEventListener("click", depositAmountPrompt);
    $('withdrawlBtn').addEventListener("click", withdrawalAmount)
    
}
window.addEventListener("load", init);

<style>body {
  width: 500px;
  margin: 0 auto;
}

#infoDisplay {
  border: 3px solid black;
  height: 250px;
}

</style>
<body>
  <button type="button" id="nameBtn" value>Name</button>
  <button type="button" id="depositBtn">Deposit</button>
  <button type="button" id="withdrawlBtn">Withdrawl</button>
  <div id="infoDisplay"></div>
</body>

Ответы [ 3 ]

1 голос
/ 19 апреля 2019

Посмотрите, как я представляю и отображаю ниже. Это на es6.

Вы получаете сообщение об ошибке: Uncaught TypeError: Cannot set property 'innerHTML' of null at financialInfoDisplay, потому что вы запускаете свой JavaScript перед созданием HTML-элементов в DOM. По этой причине он не может найти innerHTML свойство.

Возможно, вы захотите загрузить свои js в тело, чтобы вы знали, что все элементы будут готовы использовать их в JS.

 //Global Variables
let prompts = [
    {text: "Please Enter Your Name", response: ""},
    {text: "Please enter the amount of money you would like to deposit", response: ""},
    {text: "Please enter the amount of money you would like to withdrawal from your account", response: ""}
];

//Select element
const $ = (id) => {
    return document.querySelector(`#${id}`);
};

//Prompt
const prompter = (config) => {
   config.response = window.prompt(config.text);
}

//Display Prompts
const displayResponses = () => {
    let response = "";

    prompts.forEach((prompt, idx) => {
        response = response + prompt.response;
        
        document.getElementById('infoDisplay').innerHTML = response;
    });
}

//Buttons
const init = () => {
    $('nameBtn').addEventListener("click",() => { 
            prompter(prompts[0]);
            
            displayResponses();
        });

    $('depositBtn').addEventListener("click",() => {
            prompter(prompts[1]);

            displayResponses();
        });
  
    $('withdrawlBtn').addEventListener("click",() => {
            prompter(prompts[2]);

            displayResponses();
        });
};

window.addEventListener("load", init);
<style>body {
  width: 500px;
  margin: 0 auto;
}

#infoDisplay {
  border: 3px solid black;
  height: 250px;
}

</style>
<body>
  <button type="button" id="nameBtn" value>Name</button>
  <button type="button" id="depositBtn">Deposit</button>
  <button type="button" id="withdrawlBtn">Withdrawl</button>
  <div id="infoDisplay"></div>
</body>
1 голос
/ 19 апреля 2019

Вы должны вызывать financialInfoDisplay внутри каждого события щелчка и отмечать неопределенное в financialInfoDisplay, и возвращаемое значение не требуется в вашем случае.

С вашей функцией кода financialInfoDisplay() вызывать только 1 раз во время загрузки.

Не следует помещать в заголовок тег, nameBtn не сгенерировал и не может установить для него обработчик событий.

Содержание HTML:

<style>
  body {
    width: 500px;
    margin: 0 auto;
  }

  #infoDisplay {
    border: 3px solid black;
    height: 250px;
  }
</style>

<body>
  <button type="button" id="nameBtn" value>Name</button>
  <button type="button" id="depositBtn">Deposit</button>
  <button type="button" id="withdrawlBtn">Withdrawl</button>
  <div id="infoDisplay"></div>
  <script>
    //GLOBAL VARIABLES
    var userWithdrawal, userName, depositAmount;

    //GETS ELEMENT FROM DOM
    var $ = function (id) {
      "use strict";
      return window.document.getElementById(id);
    };
    //GETS USER NAME 
    function namePrompt() {
      "use strict";
      userName = window.prompt("Please enter your name");
      financialInfoDisplay();
      //return userName;
    }

    //GETS DEPOSIT AMOUNT
    function depositAmountPrompt() {
      "use strict";
      depositAmount = window.prompt("Please enter the amount of money you would like to deposit");
      //return depositAmount;
      financialInfoDisplay();

    }
    //GETS WITHDRAWAL Amount
    function withdrawalAmount() {
      "use strict";
      userWithdrawal = window.prompt("Please enter the amount of money you would like to withdrawal from your account");
      financialInfoDisplay();
      //return userWithdrawal;
    }

    //DISPLAYS THE PROMPTS WITHIN A DIV
    function financialInfoDisplay() {
      "use strict";
      if (userName != undefined) {
        var infoDisplay = window.document.getElementById('infoDisplay').innerHTML = userName;
      }
      if (depositAmount != undefined) {
        var infoDisplay = window.document.getElementById('infoDisplay').innerHTML += depositAmount;
      }
      if (userWithdrawal != undefined) {
        var infoDisplay = window.document.getElementById('infoDisplay').innerHTML += userWithdrawal;
      }

      //return infoDisplay;
    }

    //HANDLES ALL EVENT LISTENERS
    function init() {
      "use strict";
      $('nameBtn').addEventListener("click", namePrompt);
      $('depositBtn').addEventListener("click", depositAmountPrompt);
      $('withdrawlBtn').addEventListener("click", withdrawalAmount)

    }
    window.addEventListener("load", init);
  </script>
</body>

function financialInfoDisplay() {
    "use strict";
    if(userName != undefined){
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML = userName;
    }
    if(depositAmount != undefined){
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML += depositAmount;
    }
    if(userWithdrawal != undefined){
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML += userWithdrawal;
    }

    //return infoDisplay;
}

//GLOBAL VARIABLES
var userWithdrawal, userName, depositAmount;

//GETS ELEMENT FROM DOM
var $ = function (id) {
    "use strict";
    return window.document.getElementById(id); 
};
//GETS USER NAME 
function namePrompt () {
    "use strict";
    userName = window.prompt("Please enter your name");
    financialInfoDisplay();
    //return userName;
}

//GETS DEPOSIT AMOUNT
function depositAmountPrompt () {
    "use strict";
    depositAmount = window.prompt("Please enter the amount of money you would like to deposit");
    //return depositAmount;
    financialInfoDisplay();
    
}
//GETS WITHDRAWAL Amount
function withdrawalAmount () {
    "use strict";
     userWithdrawal = window.prompt("Please enter the amount of money you would like to withdrawal from your account");
     financialInfoDisplay();
     //return userWithdrawal;
}

//DISPLAYS THE PROMPTS WITHIN A DIV
function financialInfoDisplay() {
    "use strict";
    if(userName != undefined){
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML = userName;
    }
    if(depositAmount != undefined){
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML += depositAmount;
    }
    if(userWithdrawal != undefined){
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML += userWithdrawal;
    }
    
    //return infoDisplay;
}



//HANDLES ALL EVENT LISTENERS
function init() {
    "use strict";
    $('nameBtn').addEventListener("click", namePrompt);
    $('depositBtn').addEventListener("click", depositAmountPrompt);
    $('withdrawlBtn').addEventListener("click", withdrawalAmount)
    
}
window.addEventListener("load", init);
<style>body {
  width: 500px;
  margin: 0 auto;
}

#infoDisplay {
  border: 3px solid black;
  height: 250px;
}

</style>
<body>
  <button type="button" id="nameBtn" value>Name</button>
  <button type="button" id="depositBtn">Deposit</button>
  <button type="button" id="withdrawlBtn">Withdrawl</button>
  <div id="infoDisplay"></div>
</body>
0 голосов
/ 19 апреля 2019

 //Global Variables
let prompts = [
    {text: "Please Enter Your Name", response: ""},
    {text: "Please enter the amount of money you would like to deposit", response: ""},
    {text: "Please enter the amount of money you would like to withdrawal from your account", response: ""}
];

//Select element
const $ = (id) => {
    return document.querySelector("#"+id);
};

//Prompt
const prompter = (config) => {
   config.response = window.prompt(config.text);
}

//Display Prompts
const displayResponses = () => {
    let response = "";

    prompts.forEach((prompt, idx) => {
        response = response + prompt.response;
        
        document.getElementById('infoDisplay').innerHTML = response;
    });
}

//Buttons
const init = () => {
    $('nameBtn').addEventListener("click",() => { 
            prompter(prompts[0]);
            
            displayResponses();
        });

    $('depositBtn').addEventListener("click",() => {
            prompter(prompts[1]);

            displayResponses();
        });
  
    $('withdrawlBtn').addEventListener("click",() => {
            prompter(prompts[2]);

            displayResponses();
        });
};

window.addEventListener("load", init);
<style>body {
  width: 500px;
  margin: 0 auto;
}

#infoDisplay {
  border: 3px solid black;
  height: 250px;
}

</style>
<body>
  <button type="button" id="nameBtn" value>Name</button>
  <button type="button" id="depositBtn">Deposit</button>
  <button type="button" id="withdrawlBtn">Withdrawl</button>
  <div id="infoDisplay"></div>
</body>

//GLOBAL VARIABLES
var userWithdrawal, userName, depositAmount;

//GETS ELEMENT FROM DOM
var $ = function (id) {
    "use strict";
    return window.document.getElementById(id); 
};
//GETS USER NAME 
function namePrompt () {
    "use strict";
    userName = window.prompt("Please enter your name");
    financialInfoDisplay();
    //return userName;
}

//GETS DEPOSIT AMOUNT
function depositAmountPrompt () {
    "use strict";
    depositAmount = window.prompt("Please enter the amount of money you would like to deposit");
    //return depositAmount;
    financialInfoDisplay();
    
}
//GETS WITHDRAWAL Amount
function withdrawalAmount () {
    "use strict";
     userWithdrawal = window.prompt("Please enter the amount of money you would like to withdrawal from your account");
     financialInfoDisplay();
     //return userWithdrawal;
}

//DISPLAYS THE PROMPTS WITHIN A DIV
function financialInfoDisplay() {
    "use strict";
    if(userName != undefined){
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML = userName;
    }
    if(depositAmount != undefined){
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML += depositAmount;
    }
    if(userWithdrawal != undefined){
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML += userWithdrawal;
    }
    
    //return infoDisplay;
}



//HANDLES ALL EVENT LISTENERS
function init() {
    "use strict";
    $('nameBtn').addEventListener("click", namePrompt);
    $('depositBtn').addEventListener("click", depositAmountPrompt);
    $('withdrawlBtn').addEventListener("click", withdrawalAmount)
    
}
window.addEventListener("load", init);
<style>body {
  width: 500px;
  margin: 0 auto;
}

#infoDisplay {
  border: 3px solid black;
  height: 250px;
}

</style>
<body>
  <button type="button" id="nameBtn" value>Name</button>
  <button type="button" id="depositBtn">Deposit</button>
  <button type="button" id="withdrawlBtn">Withdrawl</button>
  <div id="infoDisplay"></div>
</body>

//GLOBAL VARIABLES
var userWithdrawal, userName, depositAmount;

//GETS ELEMENT FROM DOM
var $ = function (id) {
    "use strict";
    return window.document.getElementById(id); 
};
//GETS USER NAME 
function namePrompt () {
    "use strict";
    userName = window.prompt("Please enter your name");
    financialInfoDisplay();
    //return userName;
}

//GETS DEPOSIT AMOUNT
function depositAmountPrompt () {
    "use strict";
    depositAmount = window.prompt("Please enter the amount of money you would like to deposit");
    //return depositAmount;
    financialInfoDisplay();
    
}
//GETS WITHDRAWAL Amount
function withdrawalAmount () {
    "use strict";
     userWithdrawal = window.prompt("Please enter the amount of money you would like to withdrawal from your account");
     financialInfoDisplay();
     //return userWithdrawal;
}

//DISPLAYS THE PROMPTS WITHIN A DIV
function financialInfoDisplay() {
    "use strict";
    if(userName != undefined){
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML = userName;
    }
    if(depositAmount != undefined){
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML += depositAmount;
    }
    if(userWithdrawal != undefined){
    var infoDisplay = window.document.getElementById('infoDisplay').innerHTML += userWithdrawal;
    }
    
    //return infoDisplay;
}



//HANDLES ALL EVENT LISTENERS
function init() {
    "use strict";
    $('nameBtn').addEventListener("click", namePrompt);
    $('depositBtn').addEventListener("click", depositAmountPrompt);
    $('withdrawlBtn').addEventListener("click", withdrawalAmount)
    
}
window.addEventListener("load", init);
<style>body {
  width: 500px;
  margin: 0 auto;
}

#infoDisplay {
  border: 3px solid black;
  height: 250px;
}

</style>
<body>
  <button type="button" id="nameBtn" value>Name</button>
  <button type="button" id="depositBtn">Deposit</button>
  <button type="button" id="withdrawlBtn">Withdrawl</button>
  <div id="infoDisplay"></div>
</body>
...