简体   繁体   English

使用jquery在json中获取子li值及其父ul值

[英]Get the child li value with its parent ul value in a json using jquery

I have an unordered list and some li elements under the ul . 我在ul下有一个无序的列表和一些li元素。 I can not get the ul and li value as I expect. 我无法获得我期望的ulli值。 I tried several resources as below: 我尝试了以下几种资源:

http://jsfiddle.net/mohammadwali/tkhb5/ http://jsfiddle.net/mohammadwali/tkhb5/

how-do-i-convert-the-items-of-an-li-into-a-json-object-using-jquery 我如何将li的项目转换为使用jQuery的json对象

jquery-tree-traversal-nested-unordered-list-elements-to-json jQuery的树遍历嵌套到JSON的无序列表元素

My code is here as below in the fiddle: 我的代码在下面的小提琴中:

My code is in this fiddle 我的代码在这个小提琴中

My expected output is as below: 我的预期输出如下:

[{
    "id": "1",
    "category": "Parking",
    "subcategory": [
        "Street Parking",
        "Bus Parking"
    ]
}]

How can I achieve the JSON? 如何实现JSON?

Try this: 尝试这个:
Please note that I've changed the html a bit by adding a data-name to the top li elements. 请注意,通过将data-name添加到顶部li元素,我对html进行了一些更改。

var mylist = [];
$(".nameList > li").each(function() {
    mylist.push({});
  var self = mylist[mylist.length-1];
  self.subcategory = [];
  self.id = $(this).attr("value");
  self.category = $(this).attr("data-name");
  $(this).find("ul > li").each(function(){
    self.subcategory.push($(this).html());
  });
  console.log(self);
});

And here's a fiddle: 这是一个小提琴:
http://jsfiddle.net/tkhb5/262/ http://jsfiddle.net/tkhb5/262/

If you can't touch the HTML, here you have an option... 如果您无法触摸HTML,则可以在此处选择...

var myList = [];

$('ul.nameList > li').each(function() {
    myList.push({
        "id": $(this).val(),
        "category": $(this).clone().children('ul.subcatList').remove().end().text().trim(),
        "subcategory": $(this).find('ul.subcatList li').toArray().map(function(value) { return value.innerHTML; })
    });
});

... but if you can, I will put the category name in some element, to make easier to select it. ...但是,如果可以的话,我会将类别名称放在某个元素中,以使其更易于选择。 You could use... 你可以用...

<li value="1"><span class="cattitle">Parking</span>
  <ul class="subcatList">
    <li>Street Parking</li>
    <li>Bus Parking</li>
    <li>Complementary Parking</li>
  </ul>
</li>
<li value="2"><span class="cattitle">Business Services</span>
  <ul class="subcatList">
    <li>Business Center</li>
    <li>A/V Capabilities</li>
    <li>Video Conferencing</li>
  </ul>
</li>
........

... so you can simplify the jQuery... ...因此您可以简化jQuery ...

var myList = [];

$('ul.nameList > li').each(function() {
    myList.push({
        "id": $(this).val(),
        "category": $(this).children('span.classtitle').text(),
        "subcategory": $(this).find('ul.subcatList li').toArray().map(function(value) { return value.innerHTML; })
    });
});

I hope it helps 希望对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM