2010-07-01 4 views
3

내가 여기 내가 머리 DIV에서 텍스트 상자의 값에 액세스 할 및부모> 1.3

그래서 아이디 즉 panel_1 및 panel_2 필요 지금 JQuery와 1.3 버전

<div id='mainPanel'> 
    <div> 
    <h3>Head #1 <a href="#"><input type="text" value="Type 1"/> </a></h3> 

    <div> 
     <div id="panel_1"> 
      <div class="items"> 
      <div><input type='text' value="0"/></div> 
      <div><input type='text' value="1"/></div> 
      <div><input type='text' value="2"/></div> 
      <div><input type='text' value="3"/></div> 
     </div> 
     </div> 
    </div> 

    <div> 
    <h3>Head #2 <a href="#"><input type="text" value="Type 2"/> </a></h3> 
    <div> 
     <div id="panel_2"> 
      <div class="items"> 
      <div><input type='text' value="0"/></div> 
      <div><input type='text' value="1"/></div> 
      <div><input type='text' value="2"/></div> 
      <div><input type='text' value="3"/></div> 
     </div> 
     </div> 
    </div> 

    <div> 
</div> 

을 사용하고 JQuery와 자식 표기

$("#mainPanel > div > h3").each(function(index) { 

     var panelId = $(this).attr('id'); // i.e. panel_1 and all 

     // parent > child notation 
     var ele = $(this).next('div > div > div > div').each(function(index){ 


      alert($(this).children('input').val()); 


}); 

}); 
다음

내가 부모를 사용하여 결과를 가져 오는 데 실패하고> 자식 표기법 다음 코드 내가 적어해야 할 일

어떻게 H3 여기

+0

정확히 무엇이 실패합니까? 첫 번째 또는 두 번째 전화? –

+1

오타가 될 수 있지만 마크 업에 mainPanel이 클래스로 포함되어 있으며이를 ID로 참조하고 있습니다. –

답변

4

> A> INPUT의 값이 <h3> 요소가 전혀 그래서 첫 번째 선택 의지 엉망 일을 어떤 <div> 요소를 포함하지 않는 액세스 할 수 있습니다. 실제로 복잡하지 않아도됩니다.

$('#panel_1 input').each(function() { ... 

"panel_1"의 모든 입력 요소를 얻을 수 있습니다.

편집 — 대안, 지금은 당신이 무슨 뜻인지 볼 것을, "내가 ID가 필요합니다"

$('div.mainPanel div.items').each(function() { 
    var containerId = $(this).closest('div[id]').attr('id'); 
    $(this).find('input').each(function() { 
    var anInput = $(this); 
    // ... 
    }); 
}); 

단단한 용기의 구조에 의존 장기 문제에 대한 조리법처럼 보인다. 이것이 바로 "클래스"와 "id"값이 매우 유용한 이유입니다. 정확한 마크 업 구조는 바뀔 수 있지만 유연한 코드는 계속 작동 할 수 있습니다.

+0

하지만 문제는 # panel_1이 블록이 점진적으로 증가함에 따라 달라질 수 있습니다. 즉 요소를 크롤링하는 이유는 무엇입니까? – Hunt

0

내가 그래서 당신이 ID를 부여하고 패널에 포함 된 입력을 찾을 필요가있다

$(this).next('div').find('div > div > div >input').each(function(index) 
0

을 다음과 같이

$(this).next('div > div > div > div').each(function(index) 

교체가?

$('#panel_' + givenId + ' input').each(function() { ... 

또는 모든 패널을 순환하여 입력해야합니까?