2013-02-18 24 views
0

我有2行,每行有2個文本輸入。我如何通過每一行帶有「myRow」類的行,並在每行內獲得第一個具有「This」類的孩子?我能拿到第一 「這個」 類第1行的,但似乎無法得到第2行。如何獲得這些行中的每一行的第一個孩子?

My fiddle

<!doctype html> 
<html lang="en"> 
<head> 
<meta charset="utf-8" /> 
<script src="http://code.jquery.com/jquery-1.8.1.js"></script> 

<script type="text/javascript"> 

$(document).ready(function(){ 

$('#btn').click(function(){ 
    $(".myRow").each(function(){ 
     var r = $(".This").eq(0).val(); 
     alert(r); 
    }); 
}); 

}); 
</script> 

</head> 


<body> 

<div class="myRow"> 
    <input type="text" class="notThis" value="wrong!"/> 
    <input type="text" class="This" value="first one!"/> 
    <input type="text" class="This" value="almost!"/> 
</div> 

<br> 
<br> 

<div class="myRow"> 
    <input type="text" class="notThis" value="wrong!"/> 
    <input type="text" class="This" value="second one"/> 
    <input type="text" class="This" value="almost!"/> 
</div> 


<button id="btn">Submit</button> 
</body> 
</html> 

回答

3
$('#btn').click(function(){ 
    $(".myRow").each(function(){ 
     var r = $(".This:first", this).val(); 
     alert(r); 
    }); 
}); 
+0

根據各種jsPerf測試,例如:http://jsperf.com/jquery-find-vs-context-2找到比背景更快。 – 2013-02-18 17:01:05

3
$('.This:eq(0)','.myRow').css('background-color','#F00'); 

$('.myRow').find('.This:eq(0)').css('border-color','#F00'); 

$('.This:first','.myRow').css('color','#0F0'); 

$('.myRow').find('.This:first').css('font-weight','bold'); 

Working example

1

更改爲:

Demo

var r = $(this).find(".This").eq(0).val(); 

您需要查找相對於當前元素的.This,否則將始終查找第一個實例。

附註:作爲.eq(0)的替代品,您可以使用.first()

3
$('#btn').click(function(){ 
    $(".myRow").each(function(){ 
     var r = $(".This", this).eq(0).val(); 
     alert(r); 
    }); 
}); 

要選擇同時獲得,你總是可以做:

var elems = $('.This:eq(0)', '.myRow'); 

然後,你可以做到這一點,以獲得值的數組:

var values = $.map($('.This:eq(0)', '.myRow'), function(el) {return el.value}); 

FIDDLE

+0

是啊!設置上下文。 – 2013-02-18 16:56:49

+0

IMO,上下文參數是jQuery不那麼直觀的功能之一。使用'.find()'提供更清晰的代碼。 – 2013-02-18 17:10:48

+0

國際海事組織,一旦你習慣了它,情況就很好! – adeneo 2013-02-18 17:13:20

-2

這應該是訣竅:

$('#btn').click(function(){ 
    $(".myRow input:nth-child(1)").each(function(){ 
     alert($(this).val()); 
    }); 
}); 
0

您可以通過使用jQuery的工廠方法來搜索某個屬性來獲取JavaScript對象數組。例如:

var search = $('input[class="This"]'); 

您可以訪問只需使用找到的第一個:

search[0]; 

本質(這是不是這樣做的最優化的方式),你可以這樣做:

var rows = $('.myRow'); 
for(var i = 0; i < rows.length; i++) { 
    var first; 
    var row = $(rows[i]); 
    var children = row.find('input[class="This"]'); 
    // You can also do row.find('input.This'); 

    if(children.length > 0) { 
     first = children[0]; 

     // Do something with it 
    } 
} 

就像我說過的,不是最優化的方式,但是每次使用工廠方法時,都會得到一組對象,並且可以遍歷它們。

您可以通過上述HTML屬性進行搜索。

例子:

$('input[type="button"]') 
$('input[name="firstName"]') 
$('a[href="www.google.com"]') 
相關問題