简体   繁体   English

jQuery追加执行链接替换

[英]jquery append performed link replace

inputTabTitle: function(){
   origin = template.clone();
   $("#inputTabCount").change(function(){
     tabcount = parseInt($("#inputTabCount").val());
     if(tabcount > 0){
       tab = origin.find("label").text();
       for(i = 1; i <= tabcount; i ++){
         origin.find("label").text(tab + i);
         origin.find("label").attr("for", "inputTabTitle" + i);
         origin.find("input").attr("id", "inputTabTitle" + i);
         $("#tabCount").append(origin);
       }
     }
   })
 }

set n = 3 设置n = 3

When append to "#tabCount", only one element insert, actually should be three.But this code append performed like replace.Why? 当附加到“ #tabCount”时,实际上只有一个元素插入应该是三个。但是此代码附加执行的方式类似于replace。为什么? And when I add "origin = origin.clone()" before loop end, it worked well, three element inserted. 当我在循环结束之前添加“ origin = origin.clone()”时,它运行良好,插入了三个元素。

You clone your template only once. 您只能克隆模板一次。 That means: Two times you append the 'origin' to a place, where it already is. 这意味着:两次将“起源”附加到已经存在的地方。 To get, what you want (or I think you want), the cloning MUST be in the loop. 要获得您想要的(或我想您想要的),克隆必须处于循环中。

Please notice further that you pollute the GLOBAL space when you define variables such as 'tabcount' without the 'var'. 请进一步注意,当您定义变量(例如'tabcount')而不包含'var'时,会污染GLOBAL空间。 I fixed that in your source code, too. 我也将其固定在您的源代码中。

Rewrite the function like that below. 像下面这样重写函数。 But be warned: The amount of tabs is being inserted every time the value changes. 但请注意:每次值更改时都会插入选项卡的数量。 That means: 这意味着:

  • Value changes to 1 --> one tab is made 值更改为1->制作了一个选项卡
  • Value changes to 2 --> two ADDITIONAL tabs are made. 将值更改为2->将创建两个附加选项卡。

.

inputTabTitle: function(){   
    $("#inputTabCount").change(function(){
        var tabcount = parseInt($("#inputTabCount").val());

        if(tabcount > 0){
            tab = template.find("label").text();

            for(i = 1; i <= tabcount; i ++){
                var origin = template.clone();

                origin.find("label").text(tab + i);
                origin.find("label").attr("for", "inputTabTitle" + i);
                origin.find("input").attr("id", "inputTabTitle" + i);

                $("#tabCount").append(origin);
             }
         }
     })

 }

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

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