How can i give a limit to an append function with javascript?

天涯浪子 提交于 2019-12-11 03:38:59

问题


I have an append button which appends endlessly if you click it endlessly. Lets say i want this button to do this 10 times.

Let me tell you in fantasy code :p what i was thinking so that i can learn from my mistakes; ( i know its wrong but hey im learning)

thismany = 1;

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

appendbutton.onClick = disabled

thanks in advance


回答1:


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

UPDATE:

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++; 
});



回答2:


This is straight javascript. You might also consider looking into a framework such as jQuery to make it easier for you.

This assumes your HTML for the button has id="appendButton" as an attribute.

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";
     }
}



回答3:


Using your variable names:

var thismany = 0;

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

Variable encapsulated:

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

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


来源:https://stackoverflow.com/questions/4380415/how-can-i-give-a-limit-to-an-append-function-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!