如何获取列表子项的id?

时间:2013-12-17 04:01:35

标签: jquery html

我有一份清单。我想得到每个列表的子项的id。如果没有子项,那么主要列表的ID,即在我想要gwt region,country and state的位置下,在设备gateway_unit, meter_unit下,因为{{1下没有子项}和global parameters,因此需要有ID。

user

这就是我正在做的事情。我哪里错了?

<ul class="nav nav-pills nav-stacked navigation" id="configuration_sidebar_content">
    <li>
        <a>Location</a>
        <ul class="nav nav-pills nav-stacked " id="location" style="padding-left:30px;">
              <li class="active" id="Region"><a href="#region">Region</a></li>
              <li id="country"><a href="#country">Country</a></li>
              <li id="state"><a href="#state">State</a></li>
        </ul>
    </li>
    <li id="device">
        <a>Device</a>
        <ul class="nav nav-pills nav-stacked" style="padding-left:30px;">
              <li id="gateway_unit"><a href="#gateway-unit">Gateway Unit</a></li>
              <li id="meter_unit"><a href="#meter-unit">Meter Unit</a></li>
        </ul>
    </li>
    <li id="user"><a href="#user">Software User</a></li>
    <li id="global_parameters"><a href="#global-parameters">Global Parameters</a></li>
</ul>

2 个答案:

答案 0 :(得分:0)

$(function(){
    $('#configuration_sidebar_content').on('click', 'li a', function(){
        var selected_id = $(this).parent().attr('id');
        alert(selected_id)
  });
});

http://jsfiddle.net/JKeHL/

答案 1 :(得分:0)

$(function () {
    $('#configuration_sidebar_content').on('click', 'li', function (e) {
        e.stopPropagation();
        var children = $(this).find("li");
        var ids;
        if (children.length) {
            ids = $.makeArray(children.map(function () {
                return this.id;
            }));
        } else {
            ids = [this.id];
        }
        alert(ids.join(', '));
    });
});

DEMO