简体   繁体   English

为什么我不能在 for 循环中使用这个变量?

[英]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.看来我不能在 for 循环中使用var formappend ,即使当我在表单中输入一个数字时我的var formappend将一个数字返回到控制台。

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: formappend 不是一个整数,它是从这个调用返回后的一个字符串:

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

Try calling parseInt() on the result like this:尝试对结果调用 parseInt() ,如下所示:

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

Also, I think you meant to call the .on method, not the .one method on your button另外,我认为您打算调用.on方法,而不是按钮上的.one方法

First of all, you need to run 'for' loop inside the click handler.首先,您需要在点击处理程序中运行“for”循环。 Currently you bind a click handler inside a 'for' loop, so try this:目前您在“for”循环内绑定了一个点击处理程序,所以试试这个:

$('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/看看这个: https : //jsfiddle.net/s24edozb/5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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