2016-09-22 12 views
-2

後でカウントダウンで使用するHTML要素内から数値を取得するにはどうすればよいですか? document.getElementById(...)がnullであるというエラーが発生していますが、連結で何か不足していますか?ここでは、バイブルです:https://jsfiddle.net/L6ddLc0L/JavaScriptを使用してHTML要素から数値を取得

<h1 id="num">50</h1> 

<div id="status"></div> 

<button onclick='countDown(secs, "status")'>Start countdown</button> 
<button onclick='increaseNumber()'>Increase</button> 


var num = document.getElementById('num').innerHTML; 
var secs = num.parseInt(); 

function increaseNumber() { 
    secs++; 
} 

function countDown(secs, elem) { 
    var element = document.getElementById(elem); //(elem) 
    element.innerHTML = "Please wait for "+secs+" seconds"; 
    //if timer goes into negative numbers 
    if(secs < 1){ 
     clearTimeout(timer); 
     element.innerHTML = '<h2>Countdown complete!</h2>'; 
     element.innerHTML += '<a href="#">Click here now</a>'; 
    } 

    secs--; 
    var timer = setTimeout('countDown('+secs+', "'+elem+'")',1000); 
} 
+2

'のparseIntは()'必要な機能、ではない方法、すなわち 'のparseInt(文字列)'ではなく 'str.parseInt()'です。また、あなたのフィドルは、属性(onclick)などを使用してインライン、DOMゼロのイベントを使用しているときに失敗します.JSのフィドルコードはクロージャーされているので、これらの関数は呼び出されません。適切なイベント登録を代わりに使用してください。 – Utkanos

+2

あなたの質問のコードは、JSの読み込み方法を示していません。スクリプトタグはありません。 JS Fiddleのコードは、あなたが質問で説明したものとは全く異なるエラーメッセージのセットを与えます。実際の問題が何であるかを知るには、**実際の** [MCVE]を提供する必要があります。 – Quentin

+1

'document.getElementById()'が要素を見つけられない典型的な理由は、残りのHTML(および問題の要素)のロードが完了する前に、読み込まれるとすぐに ''の中でJavaScriptコードを実行することです。もちろん、あなたが共有しているコードではこの問題は発生しません。 –

答えて

1

に見える必要があり、私はそれが実際にあることをfunctionparseInt -methodを変更し、悪いsetTimeoutパラメータを固定する方法を見hereを取ります。他にも言及しておきますが、Javascriptはブラウザによって解釈されるので実行されることに注意してください。したがって、体のフィールドにアクセスするタグを<head>に含めると、ブラウザでまだ解釈されていないため、身体のフィールドにアクセスしません。

var num = document.getElementById('num').innerHTML; 
 
var secs = parseInt(num); 
 

 
function increaseNumber() { 
 
    secs++; 
 
} 
 

 
function countDown(secs, elem) { 
 
    var element = document.getElementById(elem); //(elem) 
 
    element.innerHTML = "Please wait for " + secs + " seconds"; 
 
    //if timer goes into negative numbers 
 
    if (secs < 1) { 
 
    clearTimeout(timer); 
 
    element.innerHTML = '<h2>Countdown complete!</h2>'; 
 
    element.innerHTML += '<a href="#">Click here now</a>'; 
 
    } 
 

 
    secs--; 
 
    var timer = setTimeout(function() { 
 
    countDown(secs, elem); 
 
    }, 1000); 
 
}
<h1 id="num">50</h1> 
 

 
<div id="status"></div> 
 

 
<button onclick='countDown(secs, "status")'>Start countdown</button> 
 
<button onclick='increaseNumber()'>Increase</button>

+0

'var num = document.getElementById( 'num')。innerHTML;'要素がレンダリングされた後に実行する必要があります – mplungjan

2

あなたはひどくparseInt()を使います。このように呼び出す必要があります。

var secs = parseInt(num,10); 

は、HTMLでコードが

+1

のボタンがオンになっているURLを送信することがあります。しかし、彼は* document.getElementById(...)はnull *なので、以前は他のいくつかの問題があると言います。 –

関連する問題