gpt4 book ai didi

jQuery JSON 编码输入值集

转载 作者:行者123 更新时间:2023-12-01 01:56:08 25 4
gpt4 key购买 nike

我需要序列化一组输入元素,但我一生都无法弄清楚这个简单的任务。

我可以使用以下方法成功迭代目标输入:

$("#tr_Features :input").each(function() {
...
}

这是我的代码,不起作用:

var features = "";
$("#tr_Features :input").each(function() {
features += {$(this).attr("name"): $(this).val()};
}

序列化整个表单不会给我我需要的东西。该表单的内容远不止此输入子集。这看起来应该是一个非常简单的任务,但显然在周五下午晚些时候编程并不是一件好事。

如果有帮助,这是我要定位的表单输入:

<table cellspacing="0" border="0" id="TblGrid_list" class="EditTable" cellpading="0">
<tbody><tr class="FormData" rowpos="1">
<td class="CaptionTD ui-widget-content">Cable Family</td>
<td class="DataTD ui-widget-content" style="white-space: pre;">&nbsp;<input type="text" value="" id="feature_id:8" name="feature_id:8"></td>
</tr>
<tr class="FormData" rowpos="1">
<td class="CaptionTD ui-widget-content">Material</td>
<td class="DataTD ui-widget-content" style="white-space: pre;">&nbsp;<input type="text" value="" id="feature_id:9" name="feature_id:9"></td>
</tr>
<tr class="FormData" rowpos="1">
<td class="CaptionTD ui-widget-content">Thread Size</td>
<td class="DataTD ui-widget-content" style="white-space: pre;">&nbsp;<input type="text" value="" id="feature_id:10" name="feature_id:10"></td>
</tr>
<tr class="FormData" rowpos="1">
<td class="CaptionTD ui-widget-content">Attachment Style</td>
<td class="DataTD ui-widget-content" style="white-space: pre;">&nbsp;<input type="text" value="" id="feature_id:11" name="feature_id:11"></td>
</tr>
<tr class="FormData" rowpos="1">
<td class="CaptionTD ui-widget-content">Feature</td>
<td class="DataTD ui-widget-content" style="white-space: pre;">&nbsp;<input type="text" value="" id="feature_id:12" name="feature_id:12"></td>
</tr>
<tr class="FormData" rowpos="1">
<td class="CaptionTD ui-widget-content">Comments</td>
<td class="DataTD ui-widget-content" style="white-space: pre;">&nbsp;<input type="text" value="" id="feature_id:13" name="feature_id:13"></td>
</tr>

最佳答案

编辑:

如果我正确理解你的问题,这将为你提供你想要的 json 对象。

请注意,它需要 json2 库。

var features = {};    // Create empty javascript object

$("#tr_Features :input").each(function() { // Iterate over inputs
features[$(this).attr('name')] = $(this).val(); // Add each to features object
});

var json = JSON.stringify(features); // Stringify to create json object (requires json2 library)

感谢 R0MANARMY 指出问题中预期的 json 格式。

<小时/>

您不使用 jQuery 的 .serializeArray() 有什么原因吗?功能?您可以在元素子集而不是整个表单上运行它。

$("#tr_Features :input").serializeArray();

来自文档:http://api.jquery.com/serializeArray/

.serializeArray() 方法创建一个 JavaScript 对象数组,准备好编码为 JSON 字符串。

.serializeArray() 方法可以作用于已选择单个表单元素的 jQuery 对象,例如 <input> , <textarea> ,和<select> .

关于jQuery JSON 编码输入值集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2885522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com