简体   繁体   中英

Why can't I use this variable in my for loop?

So I am having an issue with running the loop for this function. It does not appear I can use var formappend in the for loop, even though my var formappend returns a number to the console when I input a number into the form.

var formappend = $('input[name=inputform]').val();
  for (var i = 0; i < formappend; i++){
      $('button').one('click', function(i) {
            var newblock = $("<div class='block'></div>").text("");
            $('#funbox').append(newblock);
                });
  }

Thanks

formappend is not an integer, it's a string after it's returned from this call:

$('input[name=inputform]').val();

Try calling parseInt() on the result like this:

var formappend = parseInt($('input[name=inputform]').val());

Also, I think you meant to call the .on method, not the .one method on your button

First of all, you need to run 'for' loop inside the click handler. Currently you bind a click handler inside a 'for' loop, so try this:

$('button').on('click', function(i) {
    $('#funbox').text('');
    var formappend = parseInt($('input[name=inputform]').val());
    if(isNaN(formappend)) return false;

    for (var i = 0; i < formappend; i++){      
        var newblock = $("<div class='block'></div>").text("");
        $('#funbox').append(newblock);
    }
});

Check this out: https://jsfiddle.net/s24edozb/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM