2010-04-26 4 views
1

다음 기능을 구현하려고합니다. 폼 내에서 클래스 이름이 .inputField 인 필드가 여러 개인 경우 이러한 필드 중 하나를 선택하면 해당 요소와 연결된 div가 포커스가 표시되고 흐리게 표시되어야합니다. 그러나 두 번째 요소를 선택할 때 아래 코드를 구현하면 클래스가 두 클래스 모두에 적용됩니다. 내가 어디로 잘못 가고 있는지 확실하지 않니?!?!?jquery 많은 클래스 중에서 하나를 선택하십시오.

HTML 태그 :

<form class="friendlyForm" name="friendlyForm" id="friendlyForm"> 
              <ul> 
               <li> 
                <label for="testField">Test field</label> 
                <input name="testField" value="here" class="inputField" id="testField" /> 
                <div class="helper" style="display: none;">helper text here</div> 
               </li> 
               <li> 
                <label for="testField">Test field2</label> 
                <input name="testField2" value="here" class="inputField" id="testField2" /> 
                <div class="helper" style="display: none;">helper text here</div> 
               </li> 
              </ul> 
             </form> 

jQuery를 마크 업 : 여기에 모든 포인터는 크게 감상 할 수

$('.friendlyForm').find('.inputField').each(function(i) { 
    $(this).blur(); 
    $(this).focus(function() { 
     //Add the focus class and fadeIn the helper div 
     $(this).parent().addClass('focus'); 
     $(this).parent().parent().find('.helper').fadeIn(); 
    }); 
    $(this).blur(function() { 
     //Remove the focus class and fadeOut helper div 
     $(this).parent().removeClass('focus'); 
     $(this).parent().parent().find('.helper').fadeOut(); 
    }); 
}); 

.

감사합니다.

답변

2

질문을 올바르게 이해하면 트릭을해야합니다.

$('.friendlyForm .inputField').each(function() { 
    $(this).blur().focus(function() { 
    $(this).parent().addClass('focus'); 
    $(this).siblings('.helper').fadeIn(); 
    }).blur(function() { 
    $(this).parent().removeClass('focus'); 
    $(this).siblings('.helper').fadeOut(); 
    }); 
}); 

은 당신이 잘못하고있는 것은 당신이 <ul> 태그를 얻을 것이다 parent().parent()을 사용하고 있고, 따라서 그 <ul>의 모든 .helper 요소를 찾을 것입니다.

+1

실제로는'.each'가 필요 없다고 생각합니다. $ ('. friendlyForm .inputField'). blur(). focus (...). blur (...) '. –

+0

고마워요, 그 트릭을 마쳤습니다. 정말 간단! – simnom

관련 문제