2010-09-10 54 views
1

當在jquery中使用each()函數爲一組(比如說3個單選按鈕)時,如何檢索第三個按鈕,發生? 基本上,我如何從each()函數中選擇要使用的元素?如何從jquery中的每個函數獲取單選按鈕索引號

這裏是我的編碼:

HTML:

<form id="orderDefinition" name="orderDefinition"> 
    <fieldset> 
    <input type="radio" name="radioGroup" /><label for="">radio 1</label> 
    <input type="radio" name="radioGroup" /><label for="">radio 2</label> 
    <input type="radio" name="radioGroup" /><label for="">radio 3</label>  
    </fieldset> 
</form> 

的jQuery:

var radioBtnCollection = $("#orderDefinition input:radio"); 

$(radioBtnCollection).each(function(){ 
    // From here, I don't know how to get the element 
}); 

在此先感謝。

+0

這是值得注意的是,* radioBtnCollection *已經是一個jQuery對象,並且不需要再傳遞給jQuery。你可以使用'radioBtnCollection.each(function(){...});' – 2010-09-10 10:48:03

回答

2

可以使用參考元素this operator

radioBtnCollection.each(function(){ 
    alert(this.name); 
}); 

或通過使用提供給函數的參數:

radioBtnCollection.each(function(index, element){ 
    if (index == 2 && element.checked) 
     alert("3rd element is checked!"); 
}); 

如果要執行元素上的任意jQuery方法,你需要用jQuery來包裝它。對於第一個示例,$(this),對於第二個示例$(element)

你可以得到使用:eq(2),而不是每個第三單選按鈕:

if ($("#orderDefinition input:radio:eq(2)")[0].checked) 
    alert("3rd element is checked!"); 
+0

謝謝你。有用!!另一個問題(抱歉),我如何確保單選按鈕必須在jquery中檢查? – Shaoz 2010-09-10 11:27:28

+0

@Shoaz:你可以使用':checked'選擇器,例如'$('input:radio:checked')'會得到當前選中的無線電元素。 – 2010-09-10 11:34:01

+0

不是。基本上,我有這個項目,如果你從上面的代碼中選擇第3個單選按鈕,它會突出顯示一組複選框。但是現在客戶也希望當選中1個複選框時,第三個單選按鈕被自動選中,因爲它們屬於該單選按鈕。我希望這很清楚。我想知道如何使用jQuery來實現這一點。對不起,我有點新jquery ... – Shaoz 2010-09-10 11:54:28

0

使用this包裝成一個jQuery對象:

$(radioBtnCollection).each(function(){ 
    // this points to the element being iterated 
    $(this) 
}); 
相關問題