2013-12-18 4 views
2

Я просмотрел несколько вопросов, но не нашел никакой помощи. Кстати, это первый раз, когда я задаю вопрос здесь, поэтому я, возможно, не сделаю это правильно. Во всяком случае, следующая строка вызывает у меня проблемыJavascript: Uncaught TypeError: Невозможно установить свойство «innerHTML» нулевого

/* cursorPps defined above */ 
document.getElementById("cursorPps").innerHTML = cursorPps; 

Переменная cursorPps уже определена. Может ли кто-нибудь указать, какие другие возможные вещи могли вызвать эту ошибку?

Редактировать: Кстати, проблема в том, что он не обновляет значение в HTML, хотя значение переменной изменяется.

HTML:

<html> 

<head> 
<title>Potato Clicker</title> 
<link rel="stylesheet" type="text/css" href="interface.css"> 
</head> 

<body> 

<div id="left"> 
<img id="potato-img" onClick="potatoClick(clickPower)" src="stockvault-potatoes107220.jpg" width="300" height="300"> 
<br> 
<div id="mainDisplay"> 
<span id="potatoes">0</span> <br> potatoes 
<br> 
<br> 
Producing <span id="pps">0</span> potatoes per second 
<br> 
</div> 
Cursors: <span id="cursors">0</span> 
</div> 

<div id="middle"> 
<div id="buildings" onClick="buyCursor()"> &nbsp; Buy Cursor &nbsp; </div> 
</div> 


<script src="main.js"></script> 
</body> 

</html> 

Javascript:

//variables 

var potatoes = 0; //potatoes 
var clickPower = 1; //potatoes gained per click 
var pps = 0;  //potatoes per second 
var cursors = 0; //cursors 
var cursorCost;  //cost of cursor 
var cursorPps = 0; //total cursor potatoes per second 
var cursorBuy;  //cursor buy button 


//functions 

function potatoClick(number) { 

potatoes = potatoes + number; 
document.getElementById("potatoes").innerHTML = potatoes; 

} 

function buyCursor() { 

var cursorCost = Math.floor(10 * Math.pow(1.2,cursors)); 
if (potatoes >= cursorCost) { 
pps = pps - cursorPps; 
cursors = cursors + 1; 
potatoes = potatoes - cursorCost; 
cursorPps = cursorPps + 1; 
pps = pps + cursorPps; 
document.getElementById("potatoes").innerHTML = potatoes; 
document.getElementById("cursors").innerHTML = cursors; 
document.getElementById("cursorPps").innerHTML = cursorPps; 
document.getElementById("pps").innerHTML = pps; 
} 
else { 
alert("Not enough potatoes!") 
} 
var nextCost = Math.floor(100 * Math.pow(1.2,cursors));  
document.getElementById('cursorCost').innerHTML = nextCost; 
} 

window.setInterval(function() { 

if (pps > 0) { 

potatoClick(pps); 

} 

}, 1000); 
+4

У вас есть элемент с 'id' из' cursorPps' в вашем DOM? Это будет чувствительным к регистру. –

+1

Пожалуйста, поделитесь с нами HTML-кодом. – GLES

+0

Либо у вас нет элемента с идентификатором «cursorPps», либо вы пытаетесь прочитать элемент до его отображения на странице. Много дубликатов, слишком ленивых, чтобы найти. Ответьте, используйте onload или документ готов или поместите скрипты в нижней части страницы, а не в голову. – epascarello

ответ

3

Убедитесь, что

  • У вас есть элемент имеет этот идентификатор
  • элемент на странице, до этого Javascript выполняется
  • привязывается выполнение ваших JS на события (последующий из предыдущего), что происходит после того, как элемент находится на странице
  • Переменная cursorPps была заселена

Вот простой codepen, который демонстрирует способ сделать это http://codepen.io/leopic/pen/wDtIB

+0

извините, что я noob um, что вы подразумеваете под 3-м и 4-м очками? –

+0

Ваш третий вопрос не является проблемой, поскольку код запускается в ответ на событие click. Я не знаю, к чему вы относитесь к четвертому пункту. –

2

<div id="myDiv"></div> 

  • You have an element with that ID

    var length = document.querySelectorAll('#myDiv').length; 
    if(length > 0) { 
        // This element exists in the DOM tree 
    } 
    
  • You bind the execution of your JS to an event (follow-up from previous) that happens after the element is on the page

    <body> 
        <div id="myDiv"></div> 
        <script> 
         var length = document.querySelectorAll('#myDiv').length; 
         console.log(length); 
        </script> 
    </body> 
    
  • The cursorPps variable has been populated

    if(cursorPps != undefined) 
    
Смежные вопросы