2012-07-06 62 views
2

我已经申请单,我需要用克隆按钮克隆和删除按钮,删除该克隆只有我做了这个简单的脚本提交 但我相信它包含一些错误的,因为它的不工作:)jQuery的克隆形式的单场和增量ID

HTML

<form method="post"> 
    <div id="fileds"> 
    <select name="lang" id='lang'> 
    <option>select language</option> 
    </select> 
    </div> 
    </form> 
    <div class="actions"> 
     <button class="clone">Clone</button> 
     <button class="remove">Remove</button> 
    </div> 

JS

$(function(){ 
    var regex = /^(.*)(\d)+$/i; 
    var cloneIndex = $("#lang").length; 

    $("button.clone").live("click", function(){ 
     $(this).parents("#lang").clone() 
      .appendTo(".fileds") 
      .attr("id", "lang" + cloneIndex) 
      .find("*").each(function() { 
       var id = this.id || ""; 
       var match = id.match(regex) || []; 
       if (match.length == 3) { 
        this.id = match[1] + (cloneIndex); 
       } 
     }); 
     cloneIndex++; 
    }); 


}); 

我还没有找到如何编写删除代码删除按钮

谢谢

+3

'#lang'不'.clone'按钮 – Dips 2012-07-06 04:11:39

回答

2

1)#lang不是.clone

2).fields#field,因为这父是和ID

此代码应工作。住Demo

$(function() { 
    var counter = 1; 

    $(".clone").live("click", function() { 
     $("#lang:first").clone().appendTo("#fileds").addClass("lang" + counter); 
     counter++ 
    }); 

    $(".remove").live('click', function() { 
     if (counter > 1) { //Only apply if the lang field is more than 1 
      counter = counter - 1; 
      $("#lang:last").remove(); 
     } 
    }); 

});​ 
+0

的父母,这是工作十分感谢,但有关Remove按钮是什么? – Marco 2012-07-06 04:21:01

+0

见更新的代码 – Dips 2012-07-06 04:37:03

+0

这一次它不工作的所有:)不知道为什么 – Marco 2012-07-06 07:45:25

0

lang不是按键的父母,我添加了一个类和删除按钮的处理程序,试试这个:

$(function(){ 
    $(".clone").on("click", function() { // you can use `on` instead of live which is deprecated 
     var cloneIndex = $(".lang").length; // you can find the the current length of `.lang` within the handler 
     $(".lang:last").clone() // clones the last element with class of `lang` 
      .attr("id", "lang" + cloneIndex) 
      .appendTo("#fileds") // change this to id selector 
     }); 
    $("button.remove").on("click", function(){ // '.remove' click handler 
     $(".lang:last").remove() 
    }) 
}); 

DEMO

+0

其实例的工作,但是当我用它在我的网页并不在它的工作都 – Marco 2012-07-06 04:38:46

+0

@Marco注意,我已经改变了HTML标记! – undefined 2012-07-06 04:40:09

+0

确定其工作,但它删除源嫌我不想删除原来的申请 – Marco 2012-07-07 02:23:32