How can i give a limit to an append function with

2019-07-20 13:45发布

问题:

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