2012-10-18 163 views
0

我正在嘗試獲取兄弟姐妹的ID。jQuery獲取兄弟姐妹的ID號

<ul> 
    <li id="a1">a1</li> 
    <li id="a2">a2</li> 
    <li id="a3">a3</li> 
    <li id="a4">a4</li> 
</ul> 

當我點擊其中一個li的時候,我想選擇所有由逗號分隔的兄弟ID。例如,我點擊#a2並獲得#a1,#a3,#a4。謝謝。

回答

2

嘗試使用.siblings

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

    //.join would return you comma separated but 
    //if you want a space after comma then you need to pass .join(', ') 
    console.log(selEl.join(', ')); //click on #a2 and get #a1, #a3, #a4 
}); 

DEMO:http://jsfiddle.net/Lpw4u/1/

+0

我和兄弟姐妹玩耍()。 ATTR( 'id')...所以是的,這是有效的。我修改了'#'+ el.id.謝謝。 – ialphan

+0

@ialphan ahh錯過了'#'..感謝您的編輯。 –

1

通過兄弟姐妹和存儲ID在一個數組中迭代。

$("ul li").click(function(){ 
    var s = $(this).siblings(); 
    var ids= []; 
    s.each(function(){ 
     ids.push(this.id); 
    }); 
}); 
var commaSparatedIds = ids.join(','); 
0

這應該做的伎倆:

$('li').on('click', function() { 
    var ids = []; 
    var self = this; 
    $(this).siblings().each(function(){ 
     if(self != this) 
      ids.push($(this).attr('id')); 
    }); 

    alert(ids.join(',')); 
});​ 
0
$('li[id^=a]').on('click', function() { 
    alert($.makeArray(
     $(this).siblings() 
     .map(function() { 
      return $(this).attr('id'); 
     }) 
     ).join(', ')); 
});