2017-09-08 3 views
2

나는 사용자의 뷰포트 위치에 따라 CSS 클래스를 변경하기 위해 우수한 JS 플러그인 (Waypoints.js)을 오랫동안 사용해 왔습니다. 이제는이 웨이 포인트를 동적으로 생성하려고합니다.하나의 Waypoints.js에서 여러 HTML 요소를 동적으로 타겟팅하십시오.

두 가지 방법이 실패했습니다.

<div class="emp-question-set fade-up" id="emp-question-set-1"></div> 
<div class="emp-question-set fade-up" id="emp-question-set-2"></div> 
<div class="emp-question-set fade-up" id="emp-question-set-3"></div> 

접근 방식 : 1 : 생성 for 루프 getElementByID

// Number of question areas 
var questionCount = $('.emp-question-set').length; 

// Setup variables 
var waypointName, selector, selectorjQuery; 

// Start at 2, leave the first item to load normally 
for (var i = 1; i <= questionCount; i++) { 
    waypointName = 'questionsRollIn' + i; 
    selector = 'emp-question-set-' + i; 
    selectorjQuery = '#emp-question-set-' + i; 

    waypointName = new Waypoint({ 
    element: document.getElementById(selector), 
    handler: function(direction) { 
     if (direction === 'down') { 
     $(selectorjQuery).addClass('fade-up-active'); 
     } 
     if (direction === 'up') { 
     $(selectorjQuery).removeClass('fade-up-active'); 
     } 
    }, 
    offset: '70%' 
    }); 
} 

접근법 2를 사용하여 중간 점 : 웨이 포인트를 생성 희망 getElementsByClassName

questionsRollIn = new Waypoint({ 
    element: document.getElementsByClassName('emp-question-set'), 
    handler: function(direction) { 
     if (direction === 'down') { 
     $('emp-question-set').addClass('fade-up-active'); 
     } 
     if (direction === 'up') { 
     $('emp-question-set').removeClass('fade-up-active'); 
     } 
    }, 
    offset: '70%' 
    }); 

를 사용하여이 HTML을 감안할 때

여러분 중 한 분이 도와 드릴 수 있습니다. 감사합니다. 미리.

답변

4

첫 번째 접근 방식의 문제점은 JavaScript가 어떻게 작동하는지 이해하는 것이 잘못되었다고 생각합니다. Java 또는 C#과 같은 언어에서 왔을 때 때로는 혼란 스럽습니다. 로컬 변수는 이벤트 핸들러가있는 클로저의 전역에 적용됩니다. 마지막으로 이벤트를 실행하는 동안 로컬 변수 'selectorJquery'에 예상치 못한 내용이 포함될 수 있습니다. 변수의 내용을 JavaScript 콘솔에 기록하여이를 확인할 수 있습니다.

두 번째 접근 방식은 js API가 단지 하나의 요소 만 기대할 수있는 요소 집합을 바인딩하려고 시도하기 때문에 작동하지 않을 수 있습니다.

당신은이 (테스트되지 않은)처럼 시도 할 수는

// just in case we need the waypoints later on 
var waypoints = []; 

$('.emp-question-set').each(function(index, value) { 

    var that = $(value) 

    var waypoint = new Waypoint({ 
     element: value, 
     handler: function(direction) { 
      if (direction === 'down') { 
       that.addClass('fade-up-active'); 
      } 
      if (direction === 'up') { 
       that.removeClass('fade-up-active'); 
      } 
      }, 
      offset: '70%' 
    }); 
    waypoints.push(waypoint); 
}); 

이 귀하의 첫 번째 접근 방식과 다소 유사하다. 여기에있는 아이디어는 클래스 .emp-question-set 인 모든 요소를 ​​반복하고 각각에 대한 웨이 포인트 객체를 만드는 것입니다. 중요한 것은 우리가 모든 처리기가 자신의 폐쇄 상태에서 살아 있는지 확인하는 것입니다. 따라서 변수 충돌이 발생할 수 없습니다.

+0

을 변경하여 선택해야하지만, 여전히 준 솔루션은 폐쇄 문제가 해결되지 않습니다. 마지막 질문 객체를 가질 루프 끝 부분 –

0

저는 클로저 개념에 대한 첫 번째 답변에 투표했습니다.하지만 실제로 문제를 해결하지는 않은 것처럼 보입니다. 다음을 수행하면 문제를 해결할 수 있습니다.

$('.emp-question-set').each(function(){ 
    questionsRollIn = new Waypoint({ 
    element: $(this), //this is now jquery loop context(this question) 
    handler: function(direction) { 
     if (direction === 'down') { 
     $(this.element).addClass('fade-up-active'); //this is now the waypoint context 
     } 
     if (direction === 'up') { 
     $(this.element).removeClass('fade-up-active'); 
     } 
    }, 
    offset:"10%" //this can be modified based on how sensitive you want it 
    }); 
}); 

$ (this.element는) 내가 폐쇄 개념에 대한 대답을 upvoted CSS 클래스

+0

'this'를 사용하면 클로저 문제를 피할 수 있습니까? – staypuftman

+0

내가 원하는 것을 아이디어로주기 위해 답을 편집했습니다. 그래,이 말은 내가 현재 웨이 포인트 객체를 말한 것입니다. –

+0

이 모델에서 루프 내에서 함수를 만드는 방법은 무엇입니까? 여전히 작동하지 않는 것 같습니다. 또한 -이 구현에서 jQuery를 유지해야합니다. 스트레이트 JS이어야합니다. – staypuftman