如何在jquery函数$ .each($(“abc”)...中传递一个变量?

时间:2012-03-30 05:27:05

标签: javascript jquery html forms

我正在尝试迭代一堆SELECT OPTION html下拉字段,并从那些非空的字段中获取值,并为PAYPAL购物车添加隐藏字段。

我的问题是,由于某种原因,变量“curitem”未在each函数内传递,我无法像他们应该那样添加隐藏字段。我得到的只是“NaN”或“undefined”。

PAYPAL期望的是:item_name_1,item_name_2等。所有数字必须迭代+1。

我该怎么做?

提前感谢一堆

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;
    }
});

1 个答案:

答案 0 :(得分:1)

我认为你必须初始化curitem变量。

var curitem = 1;