2016-07-07 3 views
0

Wordpress 페이지가 있는데 누군가가 체크 박스를 클릭하면 2 개의 입력 필드를 표시하거나 숨길 수있는 jQuery를 실행하고 있습니다. 문제는이 코드가 내 홈페이지에서 완벽하게 실행되지만 서브 페이지에서 똑같은 작업 (동일한 html 구조체 & jquery 사용)을 시도하면 더 이상 작동하지 않는다는 것입니다. jQuery 파일의 1 부분이 해당 페이지에서 정상적으로 실행되고 심지어 파일 끝 부분에 console.log가있어 파일이 완전히로드되었음을 표시하므로 파일이로드되지 않는다는 것이 아닙니다.jQuery가 특정 Wordpress 페이지에서 실행되지 않습니다.

www.yogagids.nl 홈페이지는 "Evenementen"체크 상자를 클릭하면 2 개의 datepicker 필드가 나타나고 선택을 취소하면 숨겨집니다. 그것이 어떻게 작동해야하는지.

www.yogagids.nl/listings 이것이 작동하지 않는 페이지입니다. 같은 이야기입니다. "evenementen"체크 상자를 클릭하면 2 개의 datepicker 필드가 표시되고 숨겨집니다. 그러나이 페이지에서 아무 일도 일어나지 않습니다.

저는 정말로 여기를 잃었습니다. 모든 도움이 크게 감사 할 것입니다.

다음은이 페이지에서 실행되는 모든 코드입니다. 실제 파일은 더 크지 만 많은 문자를 게시 할 수 없습니다. https://www.yogagids.nl/ 형태에

jQuery(document).ready(function() { 

     //Create dummy input fields (altField) to show the user, this way the user sees a proper dateFormat while saving Unix Timestamp in the database. 
     //Do this for both the Add Listing page and the Search Fields 
     jQuery("#event_date_start, #filter_event_date_start").after('<input type="text" class="input-text" name="event_date_start_dummy" id="event_date_start_dummy" placeholder="Begindatum"></input>'); 
     jQuery("#event_date_end, #filter_event_date_end").after('<input type="text" class="input-text" name="event_date_end_dummy" id="event_date_end_dummy" placeholder="Einddatum"></input>'); 

     //Define Dutch format and naming for the calendars, set the calendar to use unix date (easier to compare), set an alternative field to show the proper format. 
     jQuery("#event_date_start, #filter_event_date_start").datepicker({ 
      dateFormat: "@", 
      altFormat: "dd-mm-yy", 
      altField: "#event_date_start_dummy", 
      minDate: 0, 
      dayNames: [ "Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag" ], 
      dayNamesMin: [ "Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za" ], 
      monthNames: [ "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december" ], 
      monthNamesShort: [ "jan", "feb", "maa", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec" ], 
      changeMonth: true, 
      changeYear: true 
     }); 


     //Define Dutch format and naming for the calendars, set the calendar to use unix date (easier to compare), set an alternative field to show the proper format. 
     jQuery("#event_date_end, #filter_event_date_end").datepicker({ 
      dateFormat: "@", 
      altFormat: "dd-mm-yy", 
      altField: "#event_date_end_dummy", 
      minDate: 0, 
      dayNames: [ "Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag" ], 
      dayNamesMin: [ "Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za" ], 
      monthNames: [ "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december" ], 
      monthNamesShort: [ "jan", "feb", "maa", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec" ], 
      changeMonth: true, 
      changeYear: true 
     }); 


     //Whenever a user selects a start date, set the minimum end date to the start date. 
     //This prevents users from selecting end dates that happen before the start date. 
     jQuery('#event_date_start, #filter_event_date_start').on('change', function() { 
      // Get the Start Date 
      var minDate = jQuery("#event_date_start, #filter_event_date_start").val(); 
      // Set the minimum End Date 
      jQuery("#event_date_end, #filter_event_date_end").datepicker("option", "minDate", minDate); 
     }); 


     //Chosen.js is not used on mobile devices, so running this code will interrupt the javascript. 
     //By running it only if the screen is bigger than 600px we make sure this doesnt happen. 
     if (window.innerWidth <= 600) { 
      //Do nothing 
     } else { 
      //Category dropdown uses Chosen.js, a dropdown library. 
      //When on the map view page(/listings) or submit form(/sumbit-listing) but not on my account(/my-account/listings), prevent category dropdown from closing when selecting a category. 
      if (currentLocation.toLowerCase().indexOf("listings") >= 0 && document.location.href.indexOf('my-account') === -1 || currentLocation.toLowerCase().indexOf("submit-listing") >= 0){ 
       console.log('Chosen dropdown fix active'); 

       //Source of fix: https://github.com/harvesthq/chosen/issues/1546#issuecomment-63448852 
       //By user: ronanquillevere 
       var chosen = jQuery('.job-manager-category-dropdown').chosen().data('chosen'); 
       var autoClose = false; 
       var chosen_resultSelect_fn = chosen.result_select; 
       chosen.search_contains = true; 

       chosen.result_select = function(evt) { 
        var resultHighlight = null; 

        if(autoClose === false) 
        { 
         evt['metaKey'] = true; 
         evt['ctrlKey'] = true; 

         resultHighlight = chosen.result_highlight; 
        } 

        var stext = chosen.get_search_text(); 

        var result = chosen_resultSelect_fn.call(chosen, evt); 

        if(autoClose === false && resultHighlight !== null) 
         resultHighlight.addClass('result-selected'); 

        this.search_field.val(stext);    
        this.winnow_results(); 
        this.search_field_scale(); 

        return result; 
       } 
      }; 
     } 



     //Get multiple categories from the url, that were passed from home. 
     //Source: http://stackoverflow.com/questions/22209307/how-to-get-multiple-parameters-with-same-name-from-a-url-in-javascript 
     function getQueryParams(key) { 
      qs = location.search; 
      var params = []; 
      var tokens; 
      var re = /[?&]?([^=]+)=([^&]*)/g; 
      while (tokens = re.exec(qs)) 
      { 
       if (decodeURIComponent(tokens[1]) == key) 
       params.push(decodeURIComponent(tokens[2])); 
      } 
      return params; 
     } 
     var ms_cats = getQueryParams('ms_cat'); 

     //console.log(ms_cats); 

     //Set chosen.js values by using the values that were passed in the url. 
     //Source: http://stackoverflow.com/questions/8980131/changing-selection-in-a-select-with-the-chosen-plugin 
     jQuery('.job-manager-category-dropdown ').val(ms_cats).trigger('chosen:updated'); 



     jQuery(".listingTypeSelect input[value=event]").change(function() { 
      console.log('clicked'); 
      if (!jQuery(this).is(':checked')) { 

       jQuery('.search_event_date').css('display', 'none'); 
       jQuery(".listingTypeSelect input[value=studio]").prop('disabled', false); 
       jQuery(".listingTypeSelect input[value=teacher]").prop('disabled', false); 

       if (jQuery(window).width() > 992) { 
        jQuery('.search_home_row_2 > div').css('width', '33.333%'); 
       } else { 
        jQuery('.search_home_row_2 > div').css('width', '100%'); 
       } 


      } else { 

       jQuery('.search_event_date').css('display', 'inline-block'); 
       jQuery(".listingTypeSelect input[value=studio]").attr('checked', false); // Unchecks it 
       jQuery(".listingTypeSelect input[value=teacher]").attr('checked', false); // Unchecks it 
       jQuery(".listingTypeSelect input[value=studio]").prop('disabled', true); 
       jQuery(".listingTypeSelect input[value=teacher]").prop('disabled', true); 

       if (jQuery(window).width() > 992) { 
        jQuery('.search_home_row_2 > div').css('width', '23.333%'); 
        jQuery('.search_home_row_2 .search_event_date').css('width', '30%'); 
       } else { 
        jQuery('.search_home_row_2 > div').css('width', '100%'); 
        jQuery('.search_home_row_2 .search_event_date').css('width', '100%'); 
       } 

      } 
     }); 



     //Notify that the file has loaded without problems. 
     console.log("Finished loading listify-child.js!"); 
    }); 
+0

로딩 순서 문제 인 것 같습니다. 코드가 처음 실행될 때 체크 박스가 발견되지 않습니다. 콘솔에서 수동으로 jQuery를 실행하면 ("listingTypeSelect input [value = event]") change (function() {console.log ('clicked');}); 클릭 핸들러가 해당 체크 박스에 첨부됩니다. 페이지가 어떻게 생성되는지는 모르겠지만, 오른쪽 섹션이 렌더링 된 콜백에 액세스 할 수있는 경우이를 사용하여이 스크립트를 호출해야합니다. 이 이론을 테스트하려면 console.log (jQuery (". listingTypeSelect input [value = event]"))를 추가하고 아무 것도 반환하는지 확인하십시오. – dmoo

답변

0

변경 이벤트를 바인딩 할 때 확인란이 HTML 요소가 없거나 해당 값/클래스가 누락 된 것이 거의 확실합니다. "이벤트 전파"를 활용, 부모 요소의 이벤트를 캡처 또한 on 방법을 사용하여 시도 :

 jQuery(".listingTypeSelect").on('change', 'input[value=event]', function() { 
     console.log('clicked'); 
     if (!jQuery(this).is(':checked')) { 

      jQuery('.search_event_date').css('display', 'none'); 
      jQuery(".listingTypeSelect input[value=studio]").prop('disabled', false); 
      jQuery(".listingTypeSelect input[value=teacher]").prop('disabled', false); 

      if (jQuery(window).width() > 992) { 
       jQuery('.search_home_row_2 > div').css('width', '33.333%'); 
      } else { 
       jQuery('.search_home_row_2 > div').css('width', '100%'); 
      } 


     } else { 

      jQuery('.search_event_date').css('display', 'inline-block'); 
      jQuery(".listingTypeSelect input[value=studio]").attr('checked', false); // Unchecks it 
      jQuery(".listingTypeSelect input[value=teacher]").attr('checked', false); // Unchecks it 
      jQuery(".listingTypeSelect input[value=studio]").prop('disabled', true); 
      jQuery(".listingTypeSelect input[value=teacher]").prop('disabled', true); 

      if (jQuery(window).width() > 992) { 
       jQuery('.search_home_row_2 > div').css('width', '23.333%'); 
       jQuery('.search_home_row_2 .search_event_date').css('width', '30%'); 
      } else { 
       jQuery('.search_home_row_2 > div').css('width', '100%'); 
       jQuery('.search_home_row_2 .search_event_date').css('width', '100%'); 
      } 

     } 
    }); 

IT는 DOM의 경우 높은 캡처해야 할 수도 있습니다. search_jobs div의 예

jQuery(".search_jobs").on('change', '.listingTypeSelect input[value=event]', function() { 
    //Code 
}); 
+0

신난다. 이것은 매력처럼 작동한다. 변경 이벤트를 작성하는이 방법을 알지 못했습니다. 감사 = D –

-1

은 다음과 같습니다

<form class="job_search_form" action="https://www.yogagids.nl/listings/" method="GET"> 

https://www.yogagids.nl/listings/에 :

<form class="job_filters"> 

그래서 다른 HTML 렌더링에 대한 그리고 두 번째 경우에 조치를하지 않아도 및 방법 속성.

관련 문제