2011-04-12 97 views
3

我有這個網站jQuery的各功能不能正常工作需要更換每個屬性

<form method="POST" action="" id="order" class="forms"> 
    <div> 
     <span class="col1">Ref.</span> 
     <span class="col2">Number</span> 
     <span class="col3">Color</span> 
     <span class="col4">Remarks</span> 
     <span class="col5">Prijs</span> 
    </div> 
    <div class="order"> 
     <input type="text" name="ref-1" class="col1" /> 
     <input type="text" name="num-1" class="col2" /> 
     <input type="text" name="color-1" class="col3" /> 
     <input type="text" name="remark-1" class="col4" /> 
     <input type="text" name="price-1" class="col5" /> 
    </div> 
    <a id="add" href="#">+</a> 
</form> 

而且這個jQuery

$("#add").click(function() {  
    $("#order").children(":eq(1)").clone().each(function() { 
      var index = $("#order").children().length - 1; 
      alert(index); 

     $(this).children().find(":input").each(function() { 

       alert(index); 

        $(this).attr("[name]", function(i, v) { 

         return v.substr(0, v.lastIndexOf("-") + 1) + index; 

        }).val(""); 

       }); 
    }).insertBefore("#add"); 
}); 

我需要每個輸入名稱的一部分-1替換增加後的值。 但JS不會繼續執行$(this).attr()功能 當我運行這段代碼並不顯示第二個警告框,當我點擊#add

回答

3

我沒有檢查了整個代碼的,但有一個明顯的錯誤這

.attr("[name]" 

應該

.attr("name" 

您還需要去掉.children()從線

$(this).children().find(":input") 

並使其

$(this).find(":input") 

這是因爲this是指包含輸入的div元件。通過運行.children(),它將返回input元素,並且通過執行find(),因爲它不返回任何內容,因爲find會查找選定元素內部,而不包括它在其上運行的元素。

更新的jsfiddlehttp://jsfiddle.net/gaby/TpmdP/

+0

這並沒有解決我的問題,但你是對的。 – as3student 2011-04-12 10:06:18

+0

@ as3student,用解決方案更新了答案。 – 2011-04-12 10:10:17

+0

你測試過了嗎?因爲現在我得到第二個警報,但它不會添加我克隆的元素。這真的很奇怪 – as3student 2011-04-12 11:28:50

0

刪除.find( 「:輸入」),並通過 「:輸入」 作爲參數。兒童()。 children()可以通過過濾元素來檢索子元素。