简体   繁体   English

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

[英]how to get id of siblings in array?

在此处输入图片说明 Hi can you please tell me how to get all id's in array of siblings. 嗨,您能告诉我如何获取所有ID的兄弟姐妹数组。 I got the length of sibling. 我有兄弟姐妹的长度。 Now How to get id's of that in an array . 现在如何在数组中获取ID的ID。 .

In a pic if user have 3 children. 在图片中,如果用户有3个孩子。 If it is click "First level" it show "3",If user click menu_tc_1 it show 0 .. or same in menu_tc_2 , menu_tc_3 . 如果单击“第一级”,则显示“ 3”。如果用户单击menu_tc_1则在menu_tc_2menu_tc_3显示0 ..或相同。 how to get ids of sibling in an array. 如何获取数组中的同级ID。 I try this but not get id's 我尝试这个但没有ID

$(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();
})

Use .attr() 使用.attr()

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

Use .map() and the id property 使用.map()和id属性

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

Demo: Fiddle 演示: 小提琴

Try this, 尝试这个,

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

Live Demo 现场演示

Updated according to your scenario there are no siblings of a try this, 根据您的情况进行了更新 ,没有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 更新的演示

Also if you want to use siblings then use click event on li not on anchor tag like, 另外,如果您想使用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 李兄弟姐妹演示

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

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