2014-08-29 66 views
2
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所有區域和地區像下面我如何找到當前元素的jQuery

[ 
    { 
    "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標籤我需要找到當前對象的最接近的ul,並重復li,因此我可以放在數組上。

但它不工作.. anu線索我錯過了什麼?

回答

2

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) 

DEMO

+0

精湛的解決方案的工作............. – sumit 2014-08-29 11:08:25

1

你需要先找到它的父:

$(this).parent().closest('ul') 

更妙的是使用上一個或下一個:

$(this).parent().next('ul') // to find next ul 

或者,

$(this).parent().prev('ul') //to find previous ul