JavaScript按钮没有响应

时间:2016-06-15 14:29:19

标签: javascript html button

我无法通过JavaScript按钮在点击时调用函数。我尝试了多种方法,但我认为我的代码中肯定存在其他一些问题。谢谢你的帮助。我已经搞砸了不同的按钮功能,例如' onclick'属性,但似乎没有任何作用。代码将启动一个html页面,但按钮不会做任何事情。函数永远不会被调用,但我不确定为什么。

<!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 个答案:

答案 0 :(得分:1)

那里有几个错误。我已将它缩短为相关部分。

您需要按钮上的ID。你的js代码在这里不能找到它们:

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

此外,您已经将这些元素存储在var y和n中,因此在添加事件侦听器时无需再次查询它们。

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>