アプリ版:「スタンプのみでお礼する」機能のリリースについて

JavaScript初心者です。

現在、乱数+乱数=その計算結果という単純な表示を繰り返し続けるだけのプログラムを作成したいと思っているのですが、どうも初心者なので自分のプログラムが悪いところが分からずにいます。

abc.jsというファイルともう一つtest.htmlというファイルを作成して、test.htmlのファイルから
src="abc.js"でファイルを検索して処理を実行しようとしています。そのabc.jsというファイルの中には以下のように記入しています。

window.addEventListener( "load", loadFunc, false );

function loadFunc() {

timerID = setInterval("count_up()",1000);

}

function count_up() {

var a = Math.floor( Math.random() * 100 ) + 1;
var b = Math.floor( Math.random() * 100 ) + 1;


c = new String(a);
d = new String(b);
e = new String(a+b);

document.write(c.fontcolor("red").fontsize(50) + "+".fontsize(50) + d.fontcolor("red").fontsize(50) + "=".fontsize(50) + e.fontsize(50)) ;

document.clear();

}

setIntervalというのがタイマーということがインターネットで書かれていたので、それを入れてみたのですが、計算結果は表示されるのに、1秒ごとに画面が更新されなくて、どうしたら良いのかがわかりません。

また、document.writeって連続で表示させることに適しているのかもよくわからないです。

こういう場合って、htmlの方をどうにかするのでしょうか、それともJavaだけ変更すればできるのでしょうか。

一応以下、htmlで書いてあるプログラムです。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="meiryo" />
<title>タイトル</title>
<link rel="stylesheet" href="test.css" type="text/css" />
<script type="text/javascript" src="abc.js"></script>
</head>

<body>

</body>
</html>

すみませんが、修正点を教えてください。

以上、よろしくお願いします。

A 回答 (2件)

document.write は便利な機能ですが、


残念ながらタイマーとの組み合わせはまず不可能です。

代替として DOM を使うことをオススメします。
https://developer.mozilla.org/ja/docs/DOM/DOM_Re …

その他の気になる点も含めて修正したサンプル

window.addEventListener( "load", loadFunc, false );
function loadFunc() {
_ setInterval( countUp, 1000 ); // 文字列ではなく関数が望ましい
}
function countUp() { // キャメルケースが望ましい
_ var a = Math.floor( Math.random() * 100 ) + 1;
_ var b = Math.floor( Math.random() * 100 ) + 1;
_ var top = document.body;
_ while (top.firstChild) top.removeChild(top.firstChild); // 書き込む前に画面を消去
_ function write(text, color) {
_ _ var s = document.createElement('span');
_ _ s.textContent = text;
_ _ s.style.fontSize = '300%'; // fontsize の代替
_ _ s.style.color = color? color: 'black'; // fontcolor の代替
_ _ document.body.appendChild(s); // document.write の代替
_ }
_ write(a, 'red');
_ write('+');
_ write(b, 'red');
_ write('=');
_ write(a+b);
}
    • good
    • 0

てっとりばやくはdocument.writeしないで、idをふった特定個所のinnerHTMLをかきかえてみては?

    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!