繁体   English   中英

如何获得每行的第一个孩子?

[英]How do I get the first child of each of these rows?

我有2行,每行有2个文本输入。 如何遍历带有“ myRow”类的每一行,并在每一行中获得第一个具有“ This”类的孩子? 我可以获得第1行的第一个“ This”类,但似乎无法获得第2行。

我的小提琴

<!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>
$('#btn').click(function(){
    $(".myRow").each(function(){
        var r = $(".This:first", this).val();
        alert(r);
    });
});
$('.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');

工作实例

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

小提琴

改成:

演示版

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

您需要查找.This相对于当前元素,否则它将始终找到第一个实例。

注意:作为.eq(0)的替代方法,可以使用.eq(0) .first()

您可以使用jQuery的factory方法搜索特定属性来获取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"]')

这应该可以解决问题:

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

暂无
暂无

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

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