简体   繁体   English

单击动态添加的按钮时,函数调用仅工作一次

[英]Function call only works one time when clicking a dynamically added button

OK so I have a button that was dynamically added to my HTML form. 确定,所以我有一个按钮已动态添加到我的HTML表单中。 When I click this button the JQuery below runs. 当我单击此按钮时,下面的JQuery运行。 There is a function call to checkLimit() which just basically returns a number so I know which textbox to display. 有一个对checkLimit()的函数调用,该函数基本上只是返回一个数字,因此我知道要显示哪个文本框。 The function works great the first time, but the second time it only gets to the checkLimit() call and quits. 该函数在第一次运行时效果很好,但是在第二次它仅到达checkLimit()调用并退出时。 It doesn't even call the function(I tested this by having alerts pop up you will see these are commented out below): 它甚至没有调用该函数(我通过弹出警报来测试了这一点,您将在下面看到这些注释):

JQUERY: all inside of $(document).ready(function() JQUERY:全部在$(document).ready(function()

for (var i = 0; i < 25; i++){
$("#Add_").on("click", "#plus_"+i, function(){
      checkLimit();

        if (checkLimit = 1){
        var txtbox = "<div id='Div_2_Int"+i+"'> <label> <br> </label> "
            + "<input type='text' id='Txtbox_2_Int_"+i+"' name=Txtbox_2_Int_"+i+ "'value=''>";


            $('.addSys').append(txtbox);
           }
        else if(checkLimit = 2){
        var txtbox = "<div id='Div_3_Int"+i+"'> <label> <br> </label> "
        + "<input type='text' id='Txtbox_3_Int_"+i+"' name=Txtbox_3_Int_"+i+ "'value=''>";

        $('.addSys').append(txtbox);

        }

});

}

Javascript function: JavaScript函数:

var num4 = 2;
function checkLimit() {
//alert("test2");
    if(num4 >= 4){
        alert("Only 3!");
    }else if(num4 == 3){
            num4++;
            return 2;                
    }else if(num4 == 2){
            num4++;
            return 1;
    }
    }

Two errors in your if clauses, eg: 您的if子句中有两个错误,例如:

if (checkLimit = 1){

Replace this with: 替换为:

if(checkLimit()===1){

Otherwise the variable checkLimit holding your function does not get called, but overwritten with the value 1. Additionally if you want to compare values, use the comparance operator ("===" or "==") and not the assignment operator ("="). 否则,不会调用保存函数的变量checkLimit,而是将其覆盖为值1。此外,如果要比较值,请使用比较运算符(“ ===”或“ ==”),而不要使用赋值运算符(“ =“)。 Be aware of the differences of the comparance operators, too. 也要注意比较运算符的差异。

You are not assigning the return value of checkLimit(); 您没有分配checkLimit();的返回值checkLimit(); to a variable. 到一个变量。

Try: var checkLimit = checkLimit(); 试试: var checkLimit = checkLimit();

Also, what's the point of that function if you're not passing any parameters and using a global var? 另外,如果您不传递任何参数并使用全局变量,那么该函数有什么意义呢?

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

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