2013-10-31 47 views
1

我正在使用jquery來克隆一個div,div有3個輸入字段。 因爲克隆不會更改元素的id和名稱,所以我通過查找元素來更改它。我爲每個元素都這樣做。 下面是代碼:可以重新考慮這個代碼嗎?

var idCounter = 1; 
    var noOfClonedItems = 0; 
    $('.container').on('click', '#add-new-sku', function(e){ 
    e.preventDefault(); 

    var clonedItem = $('.sku-data:first').clone(); 

    clonedItem.find('#product_skus_attributes_0_price').attr('name','product[skus_attributes][' + idCounter + '][price]').val('0.0'); 
    clonedItem.find('#product_skus_attributes_0_price').attr('id','product[skus_attributes][' + idCounter + '][price]'); 

    clonedItem.find('#product_skus_attributes_0_units_in_stock').attr('name','product[skus_attributes][' + idCounter + '][units_in_stock]').val('0'); 
    clonedItem.find('#product_skus_attributes_0_units_in_stock').attr('id','product[skus_attributes][' + idCounter + '][units_in_stock]'); 

    clonedItem.find('#product_skus_attributes_0_units_sold').attr('name','product[skus_attributes][' + idCounter + '][units_sold]').val('0'); 
    clonedItem.find('#product_skus_attributes_0_units_sold').attr('id','product[skus_attributes][' + idCounter + '][units_sold]'); 

    clonedItem.appendTo('.sku-container'); 
    idCounter++; 
    noOfClonedItems++; 
    }); 

但我嘗試優化這一技術,如果有100個元素?

我想出了這個代碼如何優化以適用於任何元素。

回答

0

你的代碼看起來合理的 - 我會在這些線上變化改變:

clonedItem.find('#product_skus_attributes_0_price').attr('name','product[skus_attributes][' + idCounter + '][price]').val('0.0'); 
clonedItem.find('#product_skus_attributes_0_price').attr('id','product[skus_attributes][' + idCounter + '][price]'); 

到這樣的事情:

clonedItem.find('#product_skus_attributes_0_price') 
.attr('name','product[skus_attributes][' + idCounter + '][price]'); 
.attr('id','product[skus_attributes][' + idCounter + '][price]') 
.val('0.0'); 

其他方式(而不是克隆對象)是使用一些模板像http://embeddedjs.com/http://mustache.github.io/這樣的引擎,它們在動態創建dom元素時非常有用(可能更具生產力)。

0
var noOfClonedItems = 0; 

$('.container').on('click', '#add-new-sku', function (e) { 
    e.preventDefault(); 
    var clonedItem = $('.sku-data:first').clone(); 
    clonedItem.find('[id^="product_skus_attributes"]').prop('id', function(_,id) { 
     var name = 'product[skus_attributes][' + (noOfClonedItems+1) + ']['+id.split(/\d\_/).pop()+']'; 
     this.name = name; 
     this.value = name=='price'?'0.0':'0'; 
     return name; 
    }).appendTo('.sku-container'); 
    noOfClonedItems++; 
}); 

FIDDLE