2016-06-15 15 views
0

JavaScriptボタンをクリックして関数を呼び出すのに問題があります。私は複数の方法を試しましたが、私のコードには他にもいくつかの問題があるはずです。ご協力いただきありがとうございます。私は 'onclick'属性のようなさまざまなボタン機能を使いこなしましたが、何も動作していないようです。コードはhtmlページを起動しますが、ボタンは何もしません。関数は決して呼び出されませんが、私は正確な理由は不明です。JavaScriptボタンが反応しない

<!DOCTYPE html> 
<html lang = "en"> 
<head> 
    <meta charset="utf-8"> 
    <title>Test Tree</title> 
</head> 
<body> 

<h1>Test Tree</h1> 

<p id="question">Ready to start the tree?</p> 

<! Below are the interactice elements> 
<button id="nextYes()">Yes</button> 
<button id="nextNo()">No</button> 


<script type="text/javascript"> 
//window.alert("hello"); 
var decision_tree = [["Ready to start the tree?"],["Node 1"],["Node 1.1", "Node  1.2"],["Node 1.1.1", "Node 1.1.2", "Node 1.2.1", "Node 1.2.2"]]; 


// this is the location in the tree, used to determine next location 
var i = 0; 
var j = 0; 

document.getElementById('y').addEventListener('click', nextYes); 
document.getElementById('n').addEventListener('click', nextNo); 

var y = document.getElementById('y'); 
var n = document.getElementById('n'); 

function nextYes() { 
    window.alert("Yes!"); 

    i++; 
    if (i==0) { 
     document.getElementById('question').innerHTML = decision_tree[i][j]; 
    } else if (i < decision_tree.length-1) { 
     j *= 2; 
     document.getElementById('question').innerHTML = decision_tree[i][j]; 
    } 
} 

function nextNo() { 

    if (i != 0 and i < decision_tree.length-1) { 
     i++; 
     j = j*2 + 1; 
     document.getElementById('question').innerHTML = decision_tree[i][j]; 
    } 
} 
</script> 

</body> 
</html> 

答えて

1

そこにはいくつかのエラーがあります。私は関連する部分だけに短縮しました。

ボタンにIDが必要です。あなたのJSコードは、そうでない場合は、ここでそれらを見つけることができません。

var y = document.getElementById('y'); 
var n = document.getElementById('n'); 

また、あなたはすでに、イベントリスナーを追加する際、再びそれらを照会するので、不要にするvar Yおよびnに保存されているこれらの要素を持っていません。 upvoteのための

var decision_tree = [["Ready to start the tree?"],["Node 1"],["Node 1.1", "Node  1.2"],["Node 1.1.1", "Node 1.1.2", "Node 1.2.1", "Node 1.2.2"]]; 
 

 

 
// this is the location in the tree, used to determine next location 
 
var i = 0; 
 
var j = 0; 
 

 
var y = document.getElementById('y'); 
 
var n = document.getElementById('n'); 
 

 
y.addEventListener('click', nextYes); 
 
n.addEventListener('click', nextNo); 
 

 

 
function nextYes() { 
 
    alert("Yes!"); 
 
} 
 

 
function nextNo() { 
 
    alert("No"); 
 
}
<h1>Test Tree</h1> 
 

 
<p id="question">Ready to start the tree?</p> 
 

 
<! Below are the interactice elements> 
 
<button id="y">Yes</button> 
 
<button id="n">No</button>

+0

感謝。これで問題が解決した場合は、回答として受け入れることを検討してください。 –

関連する問題