2017-09-03 12 views
0

다음 "태그"링크 을 클릭하면 뒤에 다음 연결을 클릭하면 "사용중"으로 표시됩니다. 내 샘플 HTML 구조는 제한된 jQuery 지식을 의미합니다. 태그 요소가 형제가 아니기 때문에 .next가 작동하지 않습니다. 최종 결과는 다음 링크를 클릭하면 '피자'라는 단어 주위의 링크를 클릭해야합니다. 모든 태그주기하려는 경우 하나의 단락다음 형제가 아닌 형제 찾기

$(".next").click(function() { 
    $(".active").next().click(); 
}); 

답변

0

이것은 모두 .back, .next.tag 요소에 특정 동작을주는 것에 관한 것입니다. 다음과 같이

조직의 코드를 유지하기 위해, 그것은 편리하고 재사용, 사용자 지정 이벤트 핸들러, 단지 이벤트 핸들러가 포함에 모든 것을 수행하는 것이 유리입니다 :

  • 는 'findPrev'이벤트 핸들러가 이전 태그를 찾을 수 세트에서 다음 세트를 찾으려면 'findNext'이벤트 핸들러가
  • 입니다.
당신이에서 BackNext 버튼을 활성화/비활성화 할 몇 가지 여분의 줄을 추가 비교적 사소한 보너스로, 그 둘레에 당신의 마음을했으면
$(document).ready(function() { 
    $(".nav .back").on('click', function(e) { 
     e.preventDefault(); 
     if(this.href) { $(".wrapper .active").triggerHandler('findPrev').click(); } 
    }); 
    $(".nav .next").on('click', function(e) { 
     e.preventDefault(); 
     if(this.href) { $(".wrapper .active").triggerHandler('findNext').click(); } 
    }); 

    $(".tag").on('findPrev', function() { // <<< custom event handler 
     var $tags = $(this).closest('.wrapper').find('.tag'); 
     var index = $tags.index(this); 
     return (index > 0) ? $tags.eq(index - 1) : $(); 
    }).on('findNext', function() { // <<< custom event handler 
     var $tags = $(this).closest('.wrapper').find('.tag'); 
     var index = $tags.index(this); 
     return (index < $tags.length) ? $tags.eq(index + 1) : $(); 
    }).on('click', function(e) { 
     e.preventDefault(); 
     $(".wrapper .tag").filter(".active").removeClass('active').end().filter(this).addClass('active'); // move the 'active' highlight 
     // desired click action here 
    }).filter(".active").trigger('click'); 
}); 

Demo

태그를 클릭하면 응답합니다. 이 부부에게 더 많은 사용자 정의 이벤트 처리기를 포함 할 수 있습니다

  • 뒤로 및 다음 요소에 대한 '사용'이벤트 처리기, 뒤로 및 다음 요소에 대한
  • 는 '사용 안 함'이벤트 핸들러.

    Demo

    노트

    $(document).ready(function() { 
        $(".nav .back").on('click', function(e) { 
         e.preventDefault(); 
         if(this.href) { $(".wrapper .active").triggerHandler('findPrev').click(); } // find previous tag and 'click' it. 
        }); 
        $(".nav .next").on('click', function(e) { 
         e.preventDefault(); 
         if(this.href) { $(".wrapper .active").triggerHandler('findNext').click(); } // find next tag and 'click' it. 
        }); 
        $(".nav .back, .nav .next").on('enable', function() { // <<< custom event handler 
         $(this).attr('href', '#'); // enable 
        }).on('disable', function() { // <<< custom event handler 
         $(this).removeAttr('href'); // disable 
        }); 
    
        $(".tag").on('findPrev', function() { // <<< custom event handler 
         var $tags = $(this).closest('.wrapper').find('.tag'); 
         var index = $tags.index(this); 
         return (index > 0) ? $tags.eq(index - 1) : $(); 
        }).on('findNext', function() { // <<< custom event handler 
         var $tags = $(this).closest('.wrapper').find('.tag'); 
         var index = $tags.index(this); 
         return (index < $tags.length) ? $tags.eq(index + 1) : $(); 
        }).on('click', function(e) { 
         e.preventDefault(); 
         $(".wrapper .tag").filter(".active").removeClass('active').end().filter(this).addClass('active'); // move the 'active' highlight 
         $(".nav .back").trigger($(this).triggerHandler('findPrev').length ? 'enable' : 'disable'); // manage the back button 
         $(".nav .next").trigger($(this).triggerHandler('findNext').length ? 'enable' : 'disable'); // manage the next button 
         // desired click action here 
        }).filter(".active").trigger('click'); // trigger 'click' to initialize everything 
    }); 
    
: 모두 .trigger().triggerHandler()

  • 사용 가능성이 혼란 스럽다. 차이점은 반환되는 것입니다. .trigger()은 항상 jQuery (연결 용)를 반환하는 반면 .triggerHandler()은 핸들러가 반환하는 값을 반환합니다.
  • HTML <button> 요소가 하이퍼 링크 대신 뒤로 및 다음 요소로 약간 단순화됩니다. 올바른 버튼은 본질적으로 href 속성을 망칠 필요없이 비활성화되거나 활성화 될 수 있습니다.
  • 커스텀 이벤트는 jQuery 플러그인으로 표현할 수 있는데, 이는 단순한 기능에 대해서는 실행 가능하지만 틀림없이 over-the-top이다.
+1

이것은 또한 나를 위해 일했습니다! 배우기를 시작하면서 어떻게 다른 것들이 가능하고 여전히 똑같은 일을하는지 봅니다. – spicedham

0

편집

내에서이 유일한 작품 같은

<div class="wrapper"> 
<p>some <a href="#" class="tag">text</a>here and more <a href="#" class="tag">text</a></p> 
<p>some <a href="#" class="tag active">text</a>here</p> 
<p>some <a href="#" class="tag">pizza</a>here and more <a href="#" class="tag">text</a></p> 
<p>some <a href="#" class="tag">text</a>here and some more <a href="#" class="tag">text</a></p> 
</div> 

<div class="nav"> 
<a href="#" class="back">Back</a> 
<a href="#" class="next">Next</a> 
</div> 

무엇인가, 당신은 그들에게 그들의 발견을 쉽게 할 수있는 사용자 지정 특성을 제공 할 수 있습니다.

코드의 주석을 참조하십시오.

실행 전체 페이지에서이 조각

$(document).ready(function(){ 
 

 
    // Get all tags. 
 
    var tagCollection = $(".tag"); 
 

 
    // Give them an "index" 
 
    tagCollection.each(function(index){ 
 
    //console.log(index); 
 
    $(this).attr("data-index",index); 
 
    }); 
 

 
    // Click handler 
 
    $(".next").click(function() { 
 
    
 
    // Get the index of the active tag +1 (for the next). 
 
    var dataIndex = parseInt($(".active").attr("data-index"))+1; 
 
    //console.log(dataIndex); 
 

 
    // If last index, back to the very first. 
 
    if(dataIndex>tagCollection.length-1){ 
 
     dataIndex = 0; 
 
    } 
 

 
    // Here, we remove the active class on the current tag 
 
    // And find the next one to add the active class on it. 
 
    // For that demo, I turned it to red. 
 
    // You may click it! 
 
    $(document).find(".active")      // Find the active one. 
 
       .removeClass("active")     // Remove the class 
 
       .closest(".wrapper")     // climb up to the wrapper 
 
       .find("[data-index='"+dataIndex+"']") // to find the next tag 
 
       .addClass("active")     // Give it the class 
 
       .click();        // And click it! 
 

 
    }); 
 
    
 
    // Tag click handler 
 
    $(".tag").click(function(){ 
 
    console.log($(this).text()); 
 
    }); 
 
    
 
});
.active{ 
 
    color:red; 
 
    font-weight:bold; 
 
    text-decoration:none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="wrapper"> 
 
    <p>some <a href="#" class="tag">text</a>here and more <a href="#" class="tag">text</a></p> 
 
    <p>some <a href="#" class="tag active">text</a>here</p> 
 
    <p>some <a href="#" class="tag">pizza</a>here and more <a href="#" class="tag">text</a></p> 
 
    <p>some <a href="#" class="tag">text</a>here and some more <a href="#" class="tag">text</a></p> 
 
</div> 
 

 
<div class="nav"> 
 
<a href="#" class="back">Back</a> 
 
<a href="#" class="next">Next</a> 
 
</div>

)
난 당신이 "뒤로"링크를 같은 논리를 적용 할 수있을 것이라 확신합니다.

관련 문제