简体   繁体   English

与子元素映射时,如何检查元素是父对象的第一个孩子?

[英]How to check element is first child of a parent when mapping with child element?

I am mapping all textarea in specific container. 我在特定容器中映射所有textarea I need to check every textarea is first element of parent( $('.services') ). 我需要检查每个textarea是parent( $('.services') )的第一个元素。 If not, then add a class to it. 如果不是,则向其中添加一个类。

There are several .services classes in page and added later after page loaded. 页面中有几个.services类,并在页面加载后添加。 Need to only show first textarea child for every .services classes. 每个.services类只需要显示第一个textarea子级。 Each .services class have many textarea. 每个.services类都有许多textarea。

$('textarea').map(function (i) {
      /* if not first textarea of parent element $('.services') */
      $(this).addClass('hide');
});

How to do this? 这个怎么做?

$('.services > textarea').filter(function() {
    return $(this).index() !== 0;
}).addClass('hide');

Try with .each() like 尝试使用.each()

$('.services textarea').each(function(){
    var indx = $(this).index(); 
    if(indx != 0) {
        $(this).addClass('hide');
    }
}); 

See this FIDDLE 看到这个FIDDLE

$(".services").find("textarea:eq(0)");

参考查找eq选择器

Why not hide all .services and then just show the first child? 为什么不隐藏所有.services ,然后仅显示第一个孩子?

$('.services').hide();
$('.services:first-child').show();

This should do it, 应该这样做

$('.services').each(function(){
   $(this).children('textarea').addClass('hide');
   $(this).children('textarea:first').removeClass('hide').show();
})

try this 尝试这个

$('.services').each(function(){
  if($(this).not(':first-child')){
    $(this).addClass('hide');
  }
}

or: 要么:

$('.services textarea:not(:first-child)').addClass('hide');

or: 要么:

$('.services').children().not(':first').addClass('hide');

Try this: 尝试这个:

$('.services textarea').each(function(){
    var textarea = $(this);
    if(!textarea.is(':first')) {
        $(this).addClass('hide');
    }
}); 

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

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