2012-02-28 2 views
1

를 사용하여 요소의 수에 따라 특정 클래스를 지정합니다 클래스를 div.content 요소로어떻게이 마크 업을했습니다 jQuery를

예를 들어, div#one에는 3,개의 요소가 있으므로 $('div#one').addClass('three-img')을 작성합니다. div#two에 2,개의 요소가 있으므로 $('div#two').addClass('two-img')을 작성하고 div#three에는 1 개만 입력 했으므로 $('div#three').addClass('one-img')을 작성합니다.

다음 jQuery 코드는 div#one에서만 작동합니다. 내가 원하는 페이지에있는 모든 div.content에 적용되는 일반적인 코드 (div.content 가진 요소 1 또는 2 또는 그 안에 3 개 a 요소를 알 수가있을 수 있습니다.

if($('#one a').length == 3){ 
    $('#one a').parent().addClass('three-img'); 
} else if($('#one a').length == 2){ 
    $('#one a').parent().addClass('two-img'); 
} else if($('#one a').length == 1){ 
    $('#one a').parent().addClass('one-img'); 
} 

답변

1

아래로 동적으로 클래스를 추가 할 수 있습니다

$(document).ready(function(){ 
     $("div.content").each(function(e){ 
      var numberofchildren = $(this).find("a").length; 
      if(numberofchildren == 3){ 
       $(this).addClass("three-img") 
      } 
      else if(numberofchildren == 2){ 
       $(this).addClass("two-img") 
      } 
      else { 
       $(this).addClass("one-img")  
      } 
     }); 
    }); 

또는 현재의 div의 어린이 :

var classes = { 1: 'one-img', 2: 'two-img', 3: 'three-img' }; 

$('div.content').each(function() { 
    var content = $(this); 
    content.addClass(classes[content.children().length]); 
}); 

점검하십시오 test here

1
$('.content').each(function(i){ 
    $(this).addClass(i + 'img'); 
}); 

같은 뭔가 ?

$(".content").each(function() { 
    $(this).addClass("img_" + $(this).find("a").length); 
}); 

수업이 img_1 명명 된 가정

1

나는 이런 식으로 할 것 , img_2

1

도움이 될까요? 당신은 클래스의 내용으로 모든 사업부을 반복을 할 수 있고 얻을 당신은 내가 이런 식으로 뭔가를 갈 것

$(document).ready(function(){ 
     $("div.content").each(function(e){ 
      var numberofchildren = $(this).find("a").length; 
      $(this).addClass("img-" + numberofchildren); 

     }); 
    }); 
1
var numbtxt = ['one', 'two', 'three']; 

$('.content').each(function(){ 
    $(this).addClass(numbtxt[$('a', this).length-1]+'-img'); 
}); 
,
+0

이것은 하나의 자식으로 div에 img 두 개의 클래스를 부여하는 식으로 그렇게하지 않을까요? – Davide

+0

댓글을 달기 전에 그것을 바 꾸었습니다. – adeneo