Eir*_*inn 10 javascript jquery
我有一系列可编辑的列表,只需按一下按钮就可以转换成某种数据结构.当它变成某种数据时,我需要一起添加重复项.
例:
应该变成某种数据列表,最后应该是这样的:
这是我的尝试:
//button click event
$(".calculate").bind("click", function(e)
{
//get the correct parent of the button
var parent = $(this).closest("#calc");
//get relevant data
parent.find(".options").each(function(index, element)
{
var opt1 = $(this).children(".opt1").children("input").val(); //weight
var opt2 = $(this).children(".opt2").children("input").val(); //ingredient
});
});
Run Code Online (Sandbox Code Playgroud)
基本上我单击按钮,上面的脚本找到所有相关数据.
如何将其转换为多维数组或可以搜索重复项的对象列表?
当我尝试创建一个动态对象时,它似乎失败了,当我创建一个多维数组进行搜索时,我被inArray无法搜索它们所阻止.
问题回顾: 我能够获得用户数据没问题.将其转换为列表并将重复项添加到一起就是问题所在.
我建议你有一个包含摘要的全局对象,它将如下所示:
$(".calculate").bind("click", function(e)
{
var fruits = {};
//get the correct parent of the button
var parent = $(this).closest("#calc");
//get relevant data
parent.find(".options").each(function(index, element)
{
var opt1 = $(this).children(".opt1").children("input").val(); //weight
var opt2 = $(this).children(".opt2").children("input").val(); //ingredient
// here is my code
if(fruits[opt2] == undefined) {
fruits[opt2] = opt1;
} else {
// assuming that opt1 is an integer
fruits[opt2] += opt1;
}
});
// use fruits variable here
});
Run Code Online (Sandbox Code Playgroud)