に基づいてグループ化し、配列を作成します。私はこの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
内の第2のオブジェクトは、"Label"
および"Options"
として次のoptgroup
を有し、以下の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);
});
をしかしoption
要素を'optgroup'ラップしません。 これを行うには巧妙な方法はありますか? よろしく
あなたは、文字列または現在のページ/ドキュメント内のHTMLを持っていますか? – trincot
@trincot現在のページ/ドキュメント、 'casperjs' – user1665355
' optgroup'は 'option'sをラップするはずですか? – connexo