2012-10-17 12 views
1

什么是写这个jQuery选择一个更好的方法:写这个jQuery选择更好的办法

// this is called when .nextButton is invoked. 
$(this).parent('.question').children('.options').children('.options > li').children('.selected').parent('li').attr('id')); 

HTML:

<div class="question" id="question1"> 
     <p>What is your age:</p> 
     <ul class="options question1Options"> 
     <li id="q1-1"><div class="radio"></div>10-20.</li> 
     <li id="q1-2"><div class="radio"></div>21-30.</li> 
     <li id="q1-3"><div class="radio"></div>31-40.</li> 
     </ul> 
     <div class="nextButton"></div> 
    </div> 

当用户点击一个这些李时珍这将增加一个选择的类(如单选按钮,只有一个被选中)。我正在尝试获取所选广播/列表的ID。谢谢。

回答

2

试试这个

$(this).closest('div.question').find('.radio.selected').closest('li').attr('id'); 

FIDDLE

+0

它的工作原理。谢谢。 – ialphan

+0

我接受这个,因为它比@Sushil建议的更合理。谢谢。 – ialphan

+0

@ialphan ..不客气:) –

1

精简代码:

$(this).siblings('.options').find('.selected').parent('li').attr('id'); 
+0

我不知道我是否看到错误的内容,但这不起作用 – NicoSantangelo

+0

为什么它应该如.options一样具有父项。 – Anoop

+0

这是行不通的。谢谢。 – ialphan