#javascript #function #global-variables #prompt
#javascript #функция #глобальные переменные #подсказка
Вопрос:
Я пытаюсь собрать информацию от пользователя с помощью подсказок, каждая из которых выполняет свои собственные функции. Каждая из этих собственных функций работает сама по себе, поскольку я их тестировал. Затем я пытаюсь отобразить информацию в Div с помощью функции financialInfoDisplay(), но я получаю следующее сообщение об ошибке
Ошибка неперехваченного типа: невозможно установить для свойства ‘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>
Комментарии:
1. Ну, во-первых, ваш код разделен на два фрагмента кода, и они не будут видеть друг друга!
2. Не могли бы вы быть более конкретными?
Ответ №1:
Вы должны вызывать financialInfoDisplay
внутри каждого события click и проверять undefined в 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>
Комментарии:
1. Код работает, когда вы тестируете его выше, однако он не работает в скобках. Это дает мне неперехваченную ошибку типа: не удается прочитать свойство ‘addEventListener’ с нулевым значением при инициализации.
2. вы должны переместить тег script перед тегом </body> не следует помещать <script></script> в тег заголовка
3. если вы введете тег заголовка, nameBtn не будет сгенерирован и не сможет установить для него обработчик событий
4. Даже когда я переместил скрипт в нижнюю часть страницы, я все равно получаю то же сообщение об ошибке.
5. На самом деле, я знаю, почему появилось это сообщение об ошибке! Это была опечатка!
Ответ №2:
Посмотрите, как я представляю и показываю ниже. Это на 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>
Ответ №3:
//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>