【发布时间】:2016-12-10 10:36:09
【问题描述】:
我有这个 html:
<select id="this_id">
<option value="0" class="empty-item">Choose Type</option>
<optgroup label="FirstGrouping"></optgroup>
<option value="2">Thing1</option>
<optgroup label="SecondGrouping"></optgroup>
<option value="8">Thing4</option>
<option value="4">Thing3</option>
<optgroup label="ThirdGrouping"></optgroup>
<option value="7">Thing8</option>
<option value="5">Thing9</option>
</select>
我要做的是创建一个如下所示的数组:
"data": [{
"Label": "FirstGrouping",
"Options": ["Thing1"]
}, {
"Label": "SecondGrouping",
"Options": ["Thing4", "Thing3"]
}, {
"Label": "ThirdGrouping",
"Options": ["Thing8", "Thing9"]
}]
optgroup 和 option 元素没有给定的顺序。所以基本上我需要首先将optgroup 和以下options 元素分组到data 数组中的第一个对象中。其中"Label" 是optgroup 和"Options" 是下一个optgroup 元素之前的所有option 元素。 data 内的第二个对象具有下一个 optgroup 作为其 "Label" 和 "Options" 是以下 option 元素,位于以下 optgroup 元素之前。等等。
如果optgroup 会包装 option 元素,那么我可以这样做:
var yearz = [];
var yearz2 = $('#this_id');
yearz2.each(function() {
var thelabel = $(this).attr('label');
var lengthch = $(this).children().length;
var thisch = $(this).children();
var theobj = [];
var alls = [];
for (var i = 0; i < lengthch; i++) {
alls.push({
"Value": thisch.eq(i).val(),
"Text": thisch.eq(i).text()
});
}
theobj = {
Label: thelabel.trim(),
Options: alls
};
yearz.push(theobj);
});
但 'optgroup' 不包装 option 元素。
有什么聪明的方法吗?
最好的问候
【问题讨论】:
-
您的 HTML 是在字符串中还是在当前页面/文档中?
-
@trincot 当前页面/文档,
casperjs -
optgroups 不是应该包装他们的options 吗? -
@sabithpocker 是的,我尝试了一些东西但没有成功。我知道如何检查
.is(),如果是optgroup或option,但可以成功分组... -
@sabithpocker 请查看我的编辑,如果
optgroup将包装option元素。但在这种情况下不是。
标签: javascript jquery arrays casperjs