在Dom事件中嵌套函数

时间:2015-07-06 20:48:24

标签: javascript

单击时需要运行onmousedown函数(更改按钮的颜色)。我需要它在另一个函数中运行 - 当单击按钮时。我怎么这样做我有点困惑?

myPunk.play = function() {
var buttons = document.getElementsByTagName("input");
for(var i = 0;i <buttons.length;i++){
    buttons[i].addEventListener("click",function(){
        var pushIt = this.id;
        console.log(this.id);
        function changeColor(){

        }
        var workIt = soundManager.createSound({
        url: "/sounds/" + pushIt +".wav"
    })
workIt.play()
})
}

}
myPunk.play()

1 个答案:

答案 0 :(得分:0)

好的,编辑了答案,包括on mouseup和mousedown事件而不是点击。你应该找这样的东西。

   myPunk.play = function() {
        function changeColor(button, color){
            button.style.background = color;
        }

        var buttons = document.getElementsByTagName("input");
        for(var i = 0; i < buttons.length; i++){
            buttons[i].addEventListener("mousedown", function(){
                changeColor(this, "#FF0000");
                var pushIt = this.id;
                var workIt = soundManager.createSound({
                    url: "/sounds/" + pushIt +".wav"
                })
                workIt.play()
            });

            buttons[i].addEventListener("mouseup", function(){
                changeColor(this, "");
            });
        }
    }
    myPunk.play()