2012-03-30 114 views
0

我想迭代一堆SELECT OPTION html下拉字段,並從那些不是空的,爲PAYPAL購物車添加一個隱藏字段

我的問題是,由於某些原因,變量「curitem」沒有在each函數中傳遞,我不能像他們那樣添加隱藏字段。應該我得到的是 「南」 或 「不確定」

什麼PAYPAL預計是:ITEM_NAME_1,item_name_2等所有數字必須由+1迭代

如何通過CA。 ñ我這樣做?

多謝提前

var curitem; 

$.each($("select"), function(index, item) { 

    var attname = $(this).attr("name"); 
    var nom = $(this).attr("data-nom"); 
    var prix = $(this).attr("data-val"); 
    var partname = attname.substring(0, 1); 
    var qte = $(this).val(); 

    // i want all my <select option> items that the NAME start with "q" AND have a value selected 
    if (partname == "q" && isNaN(qte) == false && qte > 0) { 

     // item name 
     var inp2 = document.createElement("input"); 
     inp2.setAttribute("type", "hidden"); 
     inp2.setAttribute("id", "item_name_"+curitem); 
     inp2.setAttribute("name", "item_name_"+curitem); 
     inp2.setAttribute("value", nom); 

     // amount 
     var inp3 = document.createElement("input"); 
     inp3.setAttribute("type", "hidden"); 
     inp3.setAttribute("id", "amount_"+curitem); 
     inp3.setAttribute("name", "amount_"+curitem); 
     inp3.setAttribute("value", prix); 

     // qty 
     var inp4 = document.createElement("input"); 
     inp4.setAttribute("type", "hidden"); 
     inp4.setAttribute("id", "quantity_"+curitem); 
     inp4.setAttribute("name", "quantity_"+curitem); 
     inp4.setAttribute("value", qte); 

     // add hidden fields to form 
     document.getElementById('payPalForm').appendChild(inp2); 
     document.getElementById('payPalForm').appendChild(inp3); 
     document.getElementById('payPalForm').appendChild(inp4); 


     // item number 
     curitem = curitem + 1; 
    } 
}); 
+0

爲什麼不設置'VAR curitem = 0;'? – 2012-03-30 05:31:35

+0

還有一件事:你可以通過$ .data()方法訪問你的「data-」標籤屬性 – 2012-03-30 05:33:28

+1

爲什麼不用'index'來代替?而'$('select')。each(function(index,item){...})'可能會更好。 – 2012-03-30 05:34:40

回答

1

我認爲你必須初始化curitem變量。

var curitem = 1;

+0

它在第一行代碼中被初始化。如果我把它放入jQuery中,它不起作用。 – Joel 2012-03-30 05:49:29

+0

var curitem在第一行中未定義。你需要給它一個值才能使它工作「curitem = curitem + 1;」 – 2012-03-30 14:33:58

+0

好的...這很奇怪。起初,「curitem」WAS的定義就像你告訴我的一樣。然後,當我在這裏發佈時,我只是在嘗試'var curitem;'。然後,只是玩耍,我把它改成'var i = 0;'而且它工作。我不知道我的Macrabbit Espresso軟件是不是在創建我無法'看見'的錯誤... – Joel 2012-03-30 15:28:44

相關問題