如何在数组中获取兄弟姐妹的ID?

时间:2014-04-28 04:40:52

标签: javascript jquery

enter image description here 嗨,你能告诉我如何在兄弟姐妹中获得所有身份证。我得到了兄弟姐妹的长度。现在如何获取数组中的id。

如果用户有3个孩子,则在图片中。如果单击“第一级”则显示“3”,如果用户单击menu_tc_1,则显示0 ..或menu_tc_2menu_tc_3中的$(document).on('click'," ul li > a",function(e){ //alert($(this).siblings().length); //first method.. console.log($(this).siblings().length); /*var id=$(this).parent().attr("id") || $(this).parents("ul").attr("id"); console.log(id);*/ var selEl = []; $(this).siblings().each(function (idx, el) { selEl.push('#' + el.id); }); console.log(selEl) // alert(id); // getViewFromPanel(); }) 。 如何在数组中获取兄弟ids。我试试这个,但没有得到id的

{{1}}

3 个答案:

答案 0 :(得分:4)

使用.attr()

   var id=0;
   $(this).siblings().each(function (idx, el) {
       id=el.attr('id');
       selEl.push('#' + id);
   });

答案 1 :(得分:1)

使用.map()和id属性

var selEl = $(this).parent().siblings().map(function (idx, el) {
    return this.id
}).get();

演示:Fiddle

答案 2 :(得分:1)

试试这个,

var arr=$(this).siblings().map(function () {
    return '#' + this.id;
}).get();
console.log(arr);

Live Demo

已更新根据您的方案,没有siblings of a尝试此操作,

var selEl = [];
$(this).closest('ul').find('li').each(function (idx, el) {
// -----^ using closest and find, as there are no siblings of a
 selEl.push('#' + el.id);
});
console.log(selEl);

<强> Updated demo

此外,如果您想使用siblings,请在li上使用click事件,而不是使用锚标记,

$(document).on('click', " ul li", function (e) {
    // use click event on li not on anchor tag

    //alert($(this).siblings().length);

    ......
    var selEl = [];
    $(this).siblings().each(function (idx, el) {
        selEl.push('#' + el.id);
    });
    console.log(selEl);
    .....
});

Li sibling demo