2016-07-05 4 views
0

그래, 이건 이상 하네. 나는이 특별한 질문에 대해 어떻게 말을해야할지 모르겠다. 문서가 준비되었을 때 일어나는 javascript 함수가 있습니다. 함수의 첫 번째 부분은 추가 된 html 페이지를 페이지에 포함하는 함수를 호출합니다.자바 스크립트가 경고없이 작동하지 않습니다.

다음 부분은 현재 url 페이지의 마지막 섹션과 일치하며 메뉴 항목의 부모와 함께 선택한 클래스를 제공하기 위해 메뉴에서 해당 부분을 찾습니다.

코드는 있지만 경고 문이 제거 된

alert(lastpath); 

와 함께 작동, 더 이상 작동하지 않습니다 아래 라인.

$(document).ready(function() { 

     w3IncludeHTML(); 
     lastpath=(window.location.pathname).split("/").slice(-1).pop(); 
     alert(lastpath); 
     $('a[href$="'+lastpath+'"]').attr("class","selected"); 
     $('a[href$="'+lastpath+'"]').parent(".dropdown-content").prev().attr("class","selected"); 

    }); 

여기에 무슨 일이 일어날 지 아는 사람이 있습니까?

+6

는'w3IncludeHTML는()'비동기 작업을 수행합니까 : 당신은 지금있는 당신은 (오류가 당연히 발생하지 않는 한) 모든 내용이로드되었는지 확신 할 수 있습니다, w3IncludeHTML에 콜백 함수를 전달할 수 있습니다? – Barmar

+0

테스트를 위해'$ ('a [href $ = "'+ lastpath + '"]')'(''href $ = " '+ lastpath +'"] ')를 사용하십시오. -content "). prev()')가 경고 이전에 존재합니까? – apsillers

+0

9/10 번 경고는 스크립트가로드되는 시간을 구입합니다 – dandavis

답변

0

내용 비동기 w3Data library 부하에 정의 된 기능 w3IncludeHTML. 그것은 그것의 작업을 완료 할 때 어떤 방법으로 통지하지 얻을 제공 :

function w3IncludeHTML() { 
    var z, i, a, file, xhttp; 
    z = document.getElementsByTagName("*"); 
    for (i = 0; i < z.length; i++) { 
    if (z[i].getAttribute("w3-include-html")) { 
     a = z[i].cloneNode(false); 
     file = z[i].getAttribute("w3-include-html"); 
     var xhttp = new XMLHttpRequest(); 
     xhttp.onreadystatechange = function() { 
     if (xhttp.readyState == 4 && xhttp.status == 200) { 
      a.removeAttribute("w3-include-html"); 
      a.innerHTML = xhttp.responseText; 
      z[i].parentNode.replaceChild(a, z[i]); 
      w3IncludeHTML(); 
     } 
     }  
     xhttp.open("GET", file, true); 
     xhttp.send(); 
     return; 
    } 
    } 
} 

빠른 솔루션은 위의 기능을 변경하고 스크립트에 다음 코드를 추가하는 것입니다 :

function w3IncludeHTML(callback) { 
    var z, i, file, xhttp; 
    z = document.querySelector("[w3-include-html]"); 
    if (!z) { 
    // notify caller that all is loaded 
    if (callback) callback(); 
    return; 
    } 
    file = z.getAttribute("w3-include-html"); 
    z.removeAttribute("w3-include-html"); 
    var xhttp = new XMLHttpRequest(); 
    xhttp.onreadystatechange = function() { 
    if (xhttp.readyState == 4) { 
     if (xhttp.status == 200) { 
     z.innerHTML = xhttp.responseText; 
     } 
     w3IncludeHTML(callback); 
    } 
    }  
    xhttp.open("GET", file, true); 
    xhttp.send(); 
} 

이 버전은 w3Data 라이브러리에서 제공하는 기능보다 우선하며 개선되었습니다.

$(document).ready(function() { 
    w3IncludeHTML(function() { 
     // Everything that depends on loaded content, should be done here: 
     lastpath=(window.location.pathname).split("/").slice(-1).pop(); 
     // not needed: alert(lastpath); 
     $('a[href$="'+lastpath+'"]').attr("class","selected"); 
     $('a[href$="'+lastpath+'"]').parent(".dropdown-content").prev().attr("class","selected"); 
    }); 
}); 
+0

신경 쓰지 마라,이 작동 - 기능을 편집하는 것을 잊었습니다. – alrightgame

0

the JS library from w3schools의 기능을 사용합니다. 그것은 XMLHttpRequest 객체를 사용

function w3IncludeHTML() { 
    var z, i, a, file, xhttp; 
    z = document.getElementsByTagName("*"); 
    for (i = 0; i < z.length; i++) { 
    if (z[i].getAttribute("w3-include-html")) { 
     a = z[i].cloneNode(false); 
     file = z[i].getAttribute("w3-include-html"); 
     var xhttp = new XMLHttpRequest(); 
     xhttp.onreadystatechange = function() { 
     if (xhttp.readyState == 4 && xhttp.status == 200) { 
      a.removeAttribute("w3-include-html"); 
      a.innerHTML = xhttp.responseText; 
      z[i].parentNode.replaceChild(a, z[i]); 
      w3IncludeHTML(); 
     } 
     }  
     xhttp.open("GET", file, true); 
     xhttp.send(); 
     return; 
    } 
    } 
} 

, 그래서 우리는 비동기 코드의 확신 : 그냥 자신의 코드를 살펴. 대부분이 함수를 호출 한 후 Ajax 요청의 성공 여부에 따라 코드 줄을 사용합니다. 물론 이것은 비동기 코드를 동기 코드로 취급하는 것은 좋지 않지만 alert 함수가 제공하는 지연으로 인해 (때로는;) 작동합니다!).

해결 방법 : w3IncludeHTML 함수가 수행하는 작업과 호출 후 동기 코드를 제거하는 방법을 확인하십시오. 또는 :이 함수의 ajax 부분이 완료되었을 때를 감지하는 방법을 찾으십시오. 사실, 바로 거기 :

 if (xhttp.readyState == 4 && xhttp.status == 200) { 
      a.removeAttribute("w3-include-html"); 
      a.innerHTML = xhttp.responseText; 
      z[i].parentNode.replaceChild(a, z[i]); 
      w3IncludeHTML(); 
     } 
관련 문제