2010-12-07 185 views
1

我有一个追加按钮,如果无限地点击它,它将无限追加。 可以说我想要这个按钮来做这10次。我怎样才能给JavaScript的附加功能的限制?

让我告诉你在幻想代码:p我在想什么,以便我可以从我的错误中学习; (我知道它错了,但嘿即时学习)提前

thismany = 1; 

appendbutton.onClick = "thismany = +1"; 
if{ thismany = <9} 

appendbutton.onClick = disabled 

感谢

+1

标签在获得其他SO回答者的注意力方面发挥着非常重要的作用。如果您在Javascript中提出一个问题,请包括该问题。像onclick,append,limit这样的标签也适用于其他语言。 – pyfunc 2010-12-07 18:51:36

+0

@pyfunc:对不起,我以为我确实把Javascript作为标签!归咎于我 – Opoe 2010-12-07 18:57:17

回答

2
(function(){ 
    var count = 1; 
    document.getElementById("the_node_id").onclick = function(){ 
     if(count > 10){ 
      return; 
     } 
     do_stuff(); 
     count ++; 
    }; 
})() 

更新

var count = 1; 
addEvent(append, "click", function(/* someargument */){ 
    if(count > 10){ 
     return; 
    } 
    // if you need arguments that are passed to the function, 
    // you can add them to the anonymous one and pass them 
    // to appendFunction 
    appendFunction(/* someargument */); 
    count++; 
}); 
1

使用您的变量名:

var thismany = 0; 

appendbutton.onclick = function() { 
    if (thismany++ < 10) { 
    // append things 
    } 
}; 

变量封装:

appendbutton.onclick = function() { 
    if (this.count == undefined) { 
    this.count = 0; 
    } 

    if (this.count++ < 10) { 
    // append things 
    } 
}; 
+0

谢谢!请问封装变量的优点是什么? :) – Opoe 2010-12-07 19:35:10

+1

那么,第一个方法在函数的外部范围内使用变量,第二个方法使用的事实是,在Javascript中的所有函数也是对象,因此能够具有属性。该变量仅在代码中相关,因此在这种情况下使用外部变量是不可取的。有些情况下使用外部变量会更好,如果您想要重置例如。 – Orbling 2010-12-07 20:08:06

1

这是直的javascript。你也可以考虑寻找一个像jQuery这样的框架来让你更容易。

这假定您的HTML按钮有id="appendButton"作为属性。

var count = 0; 
document.getElementById("appendButton").onClick = function(e) { 
    if(count >= 10) { 
      return false; 
    } 
    else { 
      count ++; 
      document.getElementById("id_of_thing_you_append_to").innerHTML += "Whatever you're appending"; 
    } 
}