這是不是很優雅,但你可以通過<dl>
標籤的子元素迭代,構建每套<dt>
/<dd>
標籤和.push
數組的數組到一個輸出數組:
//setup two arrays, one as a final output and one that will hold each sub-array
var output = [],
temp = [];
//iterate through each child element of the `<dl>` element
$('dl').children().each(function() {
//if this element is a `<dt>` tag
if (this.tagName == 'DT') {
//if the `temp` array is not empty
if (0 in temp) {
//`.push` the `temp` array onto the `output` array
output.push(temp);
}
//add the text of this `<dt>` tag to the `temp` array as the first key (erasing any data that was inside the `temp` array)
temp = [$(this).text()];
} else {
//if the tag found was anything other than a `<dt>` tag (I'm assuming it's a `<dd>` tag) then `.push` its text into the `temp` array
temp.push($(this).text());
}
});
//make sure to add the last iteration of the `temp` array to the `output` array
output.push(temp);
//for the structure supplied in the question, the output looks like this: [["A", "A1"], ["B", "B1", "B2"]]
這段代碼的演示,可以發現:http://jsfiddle.net/qkjKp/
你有沒有嘗試過任何東西? – talnicolas