2017-04-18 10 views
2

사용자가 목록 항목을 선택하면 해당 목록 항목과 관련된 표가 표시됩니다. 나는 두뇌 구덩이를 가지고있다. 나는 그것을 해결하는 것에 가깝다 고 생각한다. 길이가 서로 같으면 각각의 길이를 찾은 다음 표시/클릭 기능을 만듭니다. 해답은 테이블이 다른 수백 가지 목록 항목에 사용할 수있는 대답이어야합니다.목록 항목을 클릭하면 해당 목록 항목과 관련된 표가 표시됩니다.

그냥 목록에서의 위치에 따라 TBODY 요소에 목록 항목을 연결할 경우 사용하실 수 있습니다

function count(){ 
    var list = jQuery('ul li') 

    var table = jQuery('table tbody') 

    if(table.length == list.length){ 
     jQuery(list).click(function(){ 
      //show the table length that is equal to the list length 

     }) 
    } 
} 

jsfiddle

+2

어떻게해야 당신의 JS에서 루프에 대해 무엇입니까? 첫 번째 'return' 문은 즉시 주변 함수를 빠져 나올 것입니다. 루프가 필요 없으면'if (list.length === table.length)'라고 말할 수 있습니다. * "사용자가 목록 항목을 선택하면"* - 사용자가 묻는 것이 아니라 마우스를 사용하지 않는 사용자가 마우스를 사용하면 어떻게됩니까? 키보드 나 마우스에서 "클릭"할 수 있도록 li 요소에 앵커를 사용해야합니다. – nnnnnn

+0

그래, 고마워, 내가 질문을 고정 – userlkjsflkdsvm

+0

@userlkjsflkdsvm 코드가 혼란스러워, 그래서 내 자신을 썼다. 필요한 것처럼 작동합니까? http://jsbin.com/motoseyupa/edit?html,js,output – GONG

답변

6

HTML

<div> 
      <ul> 
       <li id='one'><a href="#">number</a></li> 
       <li id='two'><a href="#">othernumber</a></li> 
      </ul> 
     </div> 
     <div> 
      <table> 
       <thead> 
        <tr> 
         <th>title</th><th>title</th><th>title</th><th>title</th> 
        </tr> 
       </thead> 
       <tbody id="table1"> 
        <tr> 
         <td>blah</td> 
         <td>blah</td> 
         <td>blah</td> 
         <td>blah</td> 
        </tr> 

       </tbody> 
       <tbody id="table2" style="display:none"> 
        <tr> 
         <td>blahTwo</td> 
         <td>blahTwo</td> 
         <td>blahTwo</td> 
         <td>blahTwo</td> 
        </tr> 
       </tbody> 
      </table> 
     </div> 

JS .index() method.eq() :

var list = jQuery('ul li a') 
 
var table = jQuery('table tbody').hide() 
 
    
 
list.click(function(e) { 
 
    table.hide().eq(list.index(this)).show() 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div> 
 
    <ul> 
 
    <li id='one'><a href="#">number</a></li> 
 
    <li id='two'><a href="#">othernumber</a></li> 
 
    </ul> 
 
</div> 
 
<div> 
 
    <table> 
 
    <thead> 
 
     <tr> 
 
     <th>title</th> 
 
     <th>title</th> 
 
     <th>title</th> 
 
     <th>title</th> 
 
     </tr> 
 
    </thead> 
 
    <tbody id="table1"> 
 
     <tr> 
 
     <td>blah</td> 
 
     <td>blah</td> 
 
     <td>blah</td> 
 
     <td>blah</td> 
 
     </tr> 
 

 
    </tbody> 
 
    <tbody id="table2" style="display:none"> 
 
     <tr> 
 
     <td>blahTwo</td> 
 
     <td>blahTwo</td> 
 
     <td>blahTwo</td> 
 
     <td>blahTwo</td> 
 
     </tr> 
 
    </tbody> 
 
    </table> 
 
</div>

관련 문제