2013-02-10 1 views
0

그 안에있는 요소의 양에 따라 항상 달라지는 클래스가 있습니다. (ul> li ...) 클래스 이름은 sf-single-children-*과 같습니다. *은 항상 내부에 따라 다릅니다. . 어떻게하면 *을 자바 스크립트로 얻을 수 있습니까?이 번호에 따라 스타일을 지정할 수 있습니까?클래스 이름의 마지막 문자를 찾아서 얻으십시오

예제 코드 :

<ul class='someclass'> 
    <li class="sf-single-children-* some-other-classes-here-aswell"> 
     <ul style="width: * "> 
      <li>Item with no children element</li> 
      <li>Item with no children element</li> 
      <li>Item with no children element</li> 
      <li>Item with no children element</li> 
      <li>Item with no children element</li> 
      <li>Item with childer element which should not be counted 
       <ul> 
       <li>Item with no children element</li> 
       <li>Item with no children element</li> 
       <li>Item with no children element</li> 
       </ul> 
      </li> 
     </ul> 
    </li> 
</ul> 

난 단지 부모 <ul>이의 카운트 요소를 할 거라고하지만 난이

+2

이것은 쉬운 문제에 대한 나쁜 해결책처럼 들립니다. 자식 요소의 수를 얻기 위해'$ (element) .children(). length'와 같은 DOM 탐색을 모든 요소에 대해 사용할 수있는 방법이 없습니까? –

+0

문제는 - 코드에서 위의 구조와 같은 태그가 더 많아서 어린이를 사용할 수 없기 때문에 내가 필요로하는 것보다 엄청난 숫자를 얻는다. –

+1

필요한 요소를 얻는 방법은 항상있다.) 좀 더 완벽한 HTML 예제를 게시하고 셀 수있는 요소를 정확히 설명해 주시겠습니까? –

답변

1

가장 쉬운 해결책은 분명히 클래스 이름의 마지막 문자를 가져 오는 것입니다.

이 코드는 지정된 요소의 첫 번째 클래스를 가져오고 마지막 대시 뒤의 모든 문자를 가져옵니다. 대신 강한의 숫자로 원하는 경우이 클래스는 항상 클래스는 항상 이런 식으로

를 포맷

  • 처음

    1. :

      var number 
      function getVal() { 
          var cls = $(".someclass > li").attr('class').split(' ')[0]; 
          number = cls.substr(cls.lastIndexOf("-") + 1); 
      } 
      

      그냥 있는지 확인 , 당신은 그것을 변환해야합니다. 당신은 자녀가없는 그 얼마나 많은 요소 서버 측에서 알고있는 것처럼

      DEMO

  • 0

    당신은 같은 JQuery와 선택기를 사용할 수 있도록하는 방법을 잘 모르겠어요 어떻게 다른 방법

    $('ul > li[class^="sf-single-children-"]').each(function(){ 
        // u get all the 'li' elements with class starting with 'sf-single-children-' 
        // you can check the class with $(this).attr('class').split('-')[3]; 
    }); 
    
    +3

    '$ (this) .attr ('class'). split ('-'). pop()'훨씬 더 쉽고'-' 문자의 수에 덜 의존적입니까? –

    +0

    나는 두 번째로 @DavidThomas :-) – Maddy

    +0

    빈 배열 –

    0

    사용자의 요구 사항에 대한 귀하의 의견을 감안 아래, 다음 작동합니다 :

    ,536
    $('.someclass > li').each(function() { 
        var liCount = $('> ul > li', this).filter(function() { 
         return $(this).children('ul').length == 0; 
        }).length; 
    }); 
    

    Example fiddle

    0

    이 도움이 될 수, 그것은 요소에서 클래스 명을 추출하고, "*"당신이 사용할 수있는 설명합니다 있도록 그 이름을 파괴하는 방법을 보여줍니다.

    var haystack = document.querySelector("ul>li"); 
    var needle = haystack.getAttribute("class").split("-").pop(); 
    console.log(needle); 
    

    당신은 하나의 클래스 정의 내에서 여러 클래스를 의미하는 경우 :

    var haystack = document.querySelector("ul>li"); 
    for (var i=0; i<haystack.classList.length; i++) { 
        var needle = haystack.classList[i].split("-").pop(); 
        console.log(needle); 
    } 
    

    당신은 그 앞의 예 확장 여러 노드 의미하는 경우 :

    var haystack = document.querySelectorAll("ul>li"); 
    
    for (var h=0; h<haystack.length; h++) { 
        for (var i=0; i<haystack[h].classList.length; i++) { 
        var needle = haystack[h].classList[i].split("-").pop(); 
        console.log(needle); 
        } 
    } 
    

    예 : http://jsbin.com/igowaw/7/

    원본의 최신 수정을 기반으로 다음과 같은 작업을 수행합니까? 너 모자 찾고있어?

    var haystack = document.querySelectorAll("ul>li"); 
    for (var h=0; h<haystack.length; h++) { 
        for (var i=0; i<haystack[h].classList.length; i++) { 
        var c = haystack[h].classList[i]; 
        if (c.indexOf("sf-single-children") === 0) { 
         var needle = c.split("-").pop(); 
         console.log(needle); 
        } 
        } 
    } 
    

    예 : 당신처럼 http://jsbin.com/igowaw/8/edit

    +0

    만약 내가 여러 클래스가 있다면? –

    +0

    [Extended original answer] 첫 번째 노드에 대해 여러 클래스를 사용한다고 가정하면 ... http://jsbin.com/igowaw/4/ –

    0
    var star = $(".someclass li").attr("class").split("sf-single-children-")[1]; 
    
    0

    을 감안할 때 구조. 어떻게 sf-single-children-N을 포함하는 상기 클래스와 li 년대를 얻고 N (jQuery를 기반 솔루션)을 얻을 수 있습니다 : 당신은뿐만 아니라 클래스 이름에서 다른 클래스를 가질 수

    $('li[class*="sf-single-children-"]').each(function() { 
        var classNames = this.className.split(' '), 
         count; 
    
        for (var i=0; !count && i<classNames.length; i++) 
         if (classNames[i].indexOf('sf-single-children-') == 0) 
          count = parseInt(classNames[i].replace('sf-single-children-', ''), 10); 
    
        // there you have it in the count 
        // with `this` being the element currently being inspected 
    }); 
    

    .

    바닐라 자바 ​​스크립트 용액 (산세 jQuery를)

    var elements = document.getElementsByTagName('li'); 
    for (var i=0; i<elements.length; i++) { 
        if (elements[i].className.indexOf('sf-single-children-') < 0) 
         continue; 
    
        var classes = elements[i].className.split(' '), 
         count = 0; 
    
        for (var j=0; !count && j<classes.length; j++) 
         if (classes[j].indexOf('sf-single-children-') == 0) 
          count = parseInt(classes[j].replace('sf-single-children-', ''), 10); 
    
        // count contains the number you need 
        // elements[i] contains the element 
    }; 
    

    하지만 당신은 li 요소 당신이가 ul > li 자식 노드의 수를 찾아 원하는 주어진 클라이언트의 계산을 수행하려는 경우 count-child-nodes 클래스 이름을 가지고, 당신은 (jQuery를 함께)을 수행 할 수 있습니다

    $('li.count-child-nodes').each(function() { 
        var count = $(this).find('> ul > li').length; 
    
        // you have the count here 
    }); 
    

    ... 또는 jQuery를하지 않고 :

    var els = document.getElementsByTagName('li'); 
    for (var i=0; i<els.length; i++) { 
        var el = els[i]; 
        if (!/\bcount-child-nodes\b/.test(el.className)) 
         continue; 
    
        for (var j=0, count=0; j<el.children.length; j++) { 
         var ul = el.children[j]; 
         if (ul.nodeName.toLowerCase() != 'ul') 
          continue; 
    
         for (var k=0; k<ul.children.length; k++) { 
          if (ul.children[k].nodeName.toLowerCase() == 'li') 
           count++; 
         } 
        } 
    
        // the count has your number 
    }; 
    
    0

    여기 행간 읽기, 그것은 보인다. 당신이 HTML5로 구축하는 경우는, 따라서, 오히려 수업 시간에 그것을 전달하는 대신,이에 대한 데이터 속성을 사용하여 오프 아마 더 좋을 것 같아 :

    var x = document.querySelector("[data-single-children]"); 
    console.log(x.dataset.singleChildren); 
    
    : 당신은 그 데이터에 액세스 할 수 있습니다

    <ul class='someclass'> 
        <li class="some-other-classes-here-aswell" data-single-children="2"> 
         <ul style="width: * "> 
          <li>Item with no children element</li> 
          <li>Item with no children element</li> 
         </ul> 
        </li> 
    </ul> 
    

    예 : http://jsbin.com/uqadub/1/edit

    관련 문제