[英]How do i find closest UL tag from current element-jquery
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
,因此我可以将其放在数组上。
但这不起作用.. anu线索我错过了什么?
使用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)
您需要先找到其父级:
$(this).parent().closest('ul')
更好的是使用prev或next:
$(this).parent().next('ul') // to find next ul
要么,
$(this).parent().prev('ul') //to find previous ul
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.