如何在每次onclick事件后调用不同的函数

时间:2013-12-05 21:46:28

标签: javascript

我正在寻找一种在每次点击后调用不同功能的方法。第二次点击后我想禁用按钮。我相信我会使用条件,但我不知道如何跟踪特定元素的点击。

由于

以下是小提琴演示:http://jsfiddle.net/2w4YJ/

(function(){
    console.log("start of function");
    var studen1 = {name:"Walker", address:{street: "123 South Drive", city: 'Sarasota', state: 'FL'}, gpa: ["3.0 ", " 3.4", " 3.8"]};
    var studen2 = {name:"Christian", address:{street: "5601 Pebble Beach Ln", city: 'Sacromento', state: 'CA'}, gpa: [2.5, 3.6, 3.8]};
    var studen3 = {name:"Marisa", address:{street: "833 Golden Pond Ct", city: 'Osprey', state: 'FL'}, gpa: [4.0, 2.5, 3.0]};
    var button = document.querySelector('a');

    function loadStudent(){
        console.log("in load student");
        var eleName =    document.getElementById('name');
        var eleAddress =    document.getElementById('address');
        var eleGPA =    document.getElementById('gpa');

        eleName.innerHTML = studen1.name;
        eleAddress.innerHTML = studen1.address.street + "<br />" + studen1.address.city + "<br />" + studen1.address.state;
        eleGPA.innerHTML = studen1.gpa;
    };

    button.onclick = function(e){
        var clicks = 0;
        if(button.onclick = 1){
            console.log("1");
            loadStudent();
            clicks ++;
        } else if(clicks >= 1){
            console.log("2");
            clicks ++;
        } else{
            console.log("3");
        }
    }
})();

3 个答案:

答案 0 :(得分:0)

var clicks移出功能范围。在你的情况下,每次触发函数时,单击返回零值。

(function(){
        console.log("start of function");
        var clicks = 0;
        ...

是的,在if语句中使用=====代替=

答案 1 :(得分:0)

每次调用onclick处理程序时,您正在重新定义并将click计数器重置为zewro。尝试将clicks的声明放在事件处理程序之外:

var clicks = 0; 
button.onclick = function(){
   clicks++;
   console.log(clicks);
}

答案 2 :(得分:0)

这是一个关闭的简单示例,但我不确定您想要跟踪点击的内容,而不是在函数内部,以及您希望loadStudent()存在于哪个命名空间?

var bar;
(function foo() {
    var b = 0; /* belongs only to foo namespace */
    bar = function () { return b++ }; / bar has a copy of parent(s) function(s) memory space */
})();
window.alert(bar()); /* alerts 0  */
window.alert(bar()); /* alerts 1  */
window.alert(bar()); /* alerts 2  */