我的JS功能不会“警告”按键

时间:2014-03-18 09:11:39

标签: javascript

我有这个代码并且它似乎没有警告我按下一个键的事实(这应该在我点击Start后发生)。为什么不呢? :/

function dynamic_buttons() {
    var start_button = document.getElementById('start');
    var stop_button = document.getElementById('stop');
    start_button.onclick = log_keypress;
    stop_button.onclick = log_keypress;
    }

function log_keypress() {
    alert('click event happened'); 
    }

这是“整个”小提琴:code

4 个答案:

答案 0 :(得分:3)

您需要调用dynamic_buttons函数来绑定事件。

更新小提琴

http://fiddle.jshell.net/dQR6j/5/

function dynamic_buttons() {
var start_button = document.getElementById('start');
var stop_button = document.getElementById('stop');
start_button.onclick = log_keypress;
stop_button.onclick = log_keypress;
}

function log_keypress() {
  alert('click event happened'); 
}

dynamic_buttons(); // <--- this is important

答案 1 :(得分:1)

您没有调用dynamic_buttons()函数,因此您的事件处理程序从未被附加:

function dynamic_buttons() {
    var start_button = document.getElementById('start');
    var stop_button = document.getElementById('stop');
    start_button.onclick = log_keypress;
    stop_button.onclick = log_keypress;
    }


function log_keypress() {
    alert('click event happened'); 
    }

dynamic_buttons();

顺便说一下,您正在谈论keypress,但在您的代码中,您正在将处理程序附加到click事件。

答案 2 :(得分:0)

您尚未调用函数dynamic_buttons http://fiddle.jshell.net/dQR6j/4/

答案 3 :(得分:0)

你永远不会打电话&#34; dynamic_buttons()&#34;功能。试试这个:

function dynamic_buttons() {
    var start_button = document.getElementById('start');
    var stop_button = document.getElementById('stop');
    start_button.onclick = log_keypress;
    stop_button.onclick = log_keypress;
};

dynamic_buttons();

function log_keypress() {
    alert('click event happened'); 
}
相关问题