My html structure is like below
<h3><span class="mw-headline">Zone1</span></h3>
<ul>
<li>District 1 of Zone1</li>
<li>District 2 of Zone1</li>
<li>District 3 of Zone1</li>
</ul>
<h3><span class="mw-headline">Zone2</span></h3>
<ul>
<li>District 1 of Zone2</li>
<li>District 2 of Zone2</li>
<li>District 3 of Zone2</li>
</ul>
我需要像下面这样提取 json 上的所有区域和地区
[
{
"zone": "Zone1",
"districts": [
"District 1 of Zone1",
"District 2 of Zone1",
"District 3 of Zone1"
]
},
{
"zone": "Zone2",
"districts": [
"District 1 of Zone2",
"District 2 of Zone2",
"District 3 of Zone2"
]
}
]
我的 jquery 如下所示
$('.mw-headline').each( function() {
var state=$( this ).html();
$(this).closest('ul').find('li').each(function() { //i need the closest ul and iterate it
alert($( this ).prop('tagName'));
});
});
我需要找到当前对象最接近的 ul
并迭代 li
,作为我可以放入数组的结果。
但它不起作用..你知道我错过了什么吗?
最佳答案
使用parent
的next
选择ul
。
$(this).parent().next('ul').find('li').each(function(){...})
这将适用于完整的问题
var zones = [];
$('.mw-headline').each( function() {
var obj = {zone:'',districts:[]};
obj.zone = $(this).text();
$(this).parent().next('ul').find('li').each(function(){
obj.districts.push($(this).text());
});
zones.push(obj);
});
console.log(zones)
关于javascript - 如何从当前元素 jquery 找到最接近的 UL 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25566665/