2017-05-18 53 views
0

這是我的主頁http://www.hawaiidolphinswim.com/skin/tabid/92/Default.aspx當您單擊菜單時,它將展開,然後當您單擊隱藏的頁面上的任何其他位置時。這是它打算在整個網站上工作的方式。但是,在任何其他頁面上,例如http://www.hawaiidolphinswim.com/contact.htm,當您單擊該菜單,然後單擊該頁面上的其他任何地方時,它都不會隱藏。這是用來做此代碼:菜單按鈕在內頁中無法正常工作

function navFunction() { 
    var x = document.getElementById("nav"); 
    if (x.className === "nav"){ 
    x.className += " active"; 
    } else { 
    x.className = "nav"; 
    } 
    return false; 
} 
$(document).on("click", function(e){ 
    var y = $("#nav").children(); 
    var z = $(".menu-btn b"); 
    if ($(e.target).is(y) || $(e.target).is(z)){ 
    // console.log("navigation related"); 
    }else{ 
    // console.log("not navigation related"); 
    $(".nav").removeClass("active"); 
    } 
}); 

我怎樣才能解決這個問題,從而在菜單上內頁隱藏太多的相同方式在網頁上?

+0

您有一個頁面上的一些JS錯誤。嘗試修復它們以避免其他問題。 – tech2017

+0

請在問題本身中包含[mcve],而不僅僅是在第三方網站上(當其他任何人遇到此問題時,這可能會得到修復)。 –

回答

1

如果您在問題頁面的chrome開發工具或任何其他web調試器中執行getEventListeners(document),則會看到click事件未添加到頁面中。

換句話說,click事件偵聽器不工作,因爲您的代碼在文檔準備好之前執行。您的javascript代碼在執行之前 html dom已創建,因此無法設置偵聽器。

試試把你的代碼就緒塊裏面是這樣的:

$(document).ready(function(){ 
    // Put all your js code here 
}); 

這種方式可以確保文檔加載和事件監聽器可以正確設置。

+0

非常感謝Merunas Grincalaitis! – Parlanchina

+0

不客氣。我建議你使用普通的javascript作爲練習,因爲這樣你就會完全不知道jquery在做什麼。我也開始在開始學習jquery,但簡單的js是所有問題的答案。 –

0

您試圖獲取頁面中不存在的ID,並且它會給出錯誤並阻止腳本的功能。

var video = document.getElementById("youtube"); // this id doesn't exists in the contact me page. 

運行video代碼if語句內,檢查後如果video不爲空

if (video) { 
    var source = "https://i.ytimg.com/vi/50CxpeBse9Y/hqdefault.jpg?custom=true&w=196&h=110&stc=true&jpg444=true&jpgq=90&sp=68&sigh=UK441E57Ci7ahRUgUu9ZjjwTRUU"; //youtube thumbnail source// 
    var image = new Image(); 
    image.src = source; 
    image.addEventListener("load", function(){ 
      video.appendChild(image); 
     } 
    ); 
    video.addEventListener("click", function(){ 
     var iframe = document.createElement("iframe"); 
     iframe.setAttribute("frameborder","0"); 
     iframe.setAttribute("allowfullscreen",""); 
     iframe.setAttribute("src","https://www.youtube.com/embed/50CxpeBse9Y?autoplay=1"); //youtube video source// 
     this.innerHTML = ""; 
     this.appendChild(iframe); 
    }); 
}