【问题标题】:How to iterate through html element and capture values for id and value using javascript如何使用 javascript 遍历 html 元素并捕获 id 和 value 的值
【发布时间】:2012-03-22 05:43:10
【问题描述】:

我有一种情况,数据从 ajax/json 调用到数据库动态显示在屏幕上。然后数据可以由用户操作,并在屏幕上显示为 li 项目。数据由 ddl 触发并且是动态的(意味着可以根据 ddl 选择显示各种项目)。我需要捕获每个项目的值和 id。我想序列化这些值并传递给 db,但这样做时遇到了问题。请帮忙。

最初构建 HTML/填充数据的 Javascript:

for (var i = 0; i < items.length; i++) {
                            form += '<li><input class="number" name="product-item_' + items[i].RiskID + '" id="product-item_' + items[i].RiskID + '" type="text" value="' + items[i].DefaultFee + '" /> ' + items[i].Description + '</li>';

                        }

调用 Javascript 来获取信息并在客户端保存更改:

var getInfo = function () {
                    return {
                        ProductID: $('#ctl00_ContentPlaceHolder1_Manage1_ddlProducts').val(),
                        ProductDescription: $('#ctl00_ContentPlaceHolder1_Manage1_ddlProducts option:selected').text(),
                        ProductItems: $("#ProductItems").html(),
                        //The code below is blowing up:
                        ItemValue: $("#li").each(function (n) { $(this).attr('value'); })
                       //This will also have to be done
                       ItemID: $("#li").each(function (n) { var currId = $(this).attr('id'); var removeTxt = "product-item_"; var currID = currId.replace(removeTxt,""); })
                    };
                };

我的方法可能有缺陷。我愿意修改我当前的方法。我想要的序列化结果的一个例子是:

[{"ProductID": "Xa","ItemID":"Ya1","ItemValue":"Za1","ItemID":"Ya2","ItemValue":"Za2"},
 {"ProductID": "Xb","ItemID":"Yb1","ItemValue":"Zb1"}].

(其中 Xa、Ya、Za 等表示值。)

提前感谢您的帮助。

【问题讨论】:

标签: javascript jquery html ajax json


【解决方案1】:

这段代码:

ItemValue: $("#li").each(function (n) { $(this).attr('value'); })

将返回一个 jQuery 对象,而不是我认为您期望的数组。改用$.map

ItemValue: $.map($("#li"),function(el,n) { return $(this).attr('value'); })

或者,您可以将数组.join(',') 映射为单个逗号分隔的字符串。

ItemID的映射函数的转换留给读者练习。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多