如何使用javascript限制附加功能?

时间:2010-12-07 18:48:42

标签: javascript onclick append limit

如果你无休止地点击它,我会有一个无限追加的追加按钮。 让我们说我想要这个按钮10次。

让我用幻想代码告诉你:p我在想什么,这样我才能从错误中吸取教训; (我知道它错了,但是我正在学习)

thismany = 1;

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

appendbutton.onClick = disabled

提前致谢

3 个答案:

答案 0 :(得分: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 :(得分: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
  }
};

答案 2 :(得分: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";
     }
}