2014-10-28 8 views
0

이 작은 코드는 작동하지 않습니다. 나는 기본적으로 클릭 된 ahref의 형제를 얻으려고 시도하지만 클릭 한 요소 자체를 반환합니다 (이것을 테스트하려면 console.log() 사용).jQuery가 형제 또는 가장 가까운 요소가 작동하지 않음

$('.script-vote').click(function(e) { 
    e.preventDefault(); 
    var href = $(this); 

    href.siblings('.script-vote') //This doesn't work 
     .removeClass('active'); 

    href.closest('.script-vote') //This doesn't work 
     .removeClass('active'); 
}); 

그리고 내 HTML : 나는 .script-vote.up 요소를 클릭 클릭하면

<div class="one-half t-center"> 
    <a href="..." class="script-vote up" title="Upvoten"> 
     <i class="fa fa-thumbs-o-up"></i> 
     <span class="score"><?=$post->getUpVotes()?></span> 
    </a> 
</div> 
<div class="one-half t-center"> 
    <a href="..." class="script-vote down" title="Downvoten"> 
     <i class="fa fa-thumbs-o-down"></i> 
     <span class="score"><?=$post->getUpVotes()?></span> 
    </a> 
</div> 

그래서, 내가 .script-vote.downactive 클래스를 제거 할. 미리 감사드립니다.

+2

이들은 형제가 아니며 서로 다른 부모를가집니다. –

+1

'a' 태그는 형제가 없으며 가장 가까운 노드 만 상위 체인을 검사합니다.'href.parent(). next(). find ('.script -vote ')' – OJay

+0

빠른 반응을 가져 주셔서 감사합니다. 지금 받으십시오. 내 문제를 해결하기 위해'href.parent(). siblings(). find ('. script-vote'). removeClass ('active')'를 사용했다. – JasonK

답변

1

< HTML의 a> 요소에는 형제가 없습니다. 그러나 부모님들은 그렇게합니다.

<div class="voting-container"> 
<div class="one-half t-center"> 
    <a href="..." class="script-vote up" title="Upvoten"> 
     <i class="fa fa-thumbs-o-up"></i> 
     <span class="score"><?=$post->getUpVotes()?></span> 
    </a> 
</div> 
<div class="one-half t-center"> 
    <a href="..." class="script-vote down" title="Downvoten"> 
     <i class="fa fa-thumbs-o-down"></i> 
     <span class="score"><?=$post->getUpVotes()?></span> 
    </a> 
</div> 
</div> 
당신은 예로서 jQuery를 함께 다음과 같은 자바 스크립트를 참조 할 수 있습니다

:

$(".script-vote").click(function(){ 

    var otherVotingButton = $(this).parent().siblings(".one-half").first().find(".script-vote"); 

    otherVotingButton.css("background-color","red");  

    otherVotingButton.href="#"; 
    otherVotingButton 
     .off() //remove original event handler 
     .click(function() { alert("you already voted!");}); 
}); 

부모의 형제 자매를 가져 오기, 다음을 얻을 그들은 그랜드 부모 사업부에 동봉되어 있는지 확인합니다 스크립트 - 투표 <> 요소 안에 있습니다.

+1

내 문제는 해결되었지만 노력과 몇 가지 추가 정보로이 대답을 받아 들일 것입니다 :-). – JasonK