2013-07-30 116 views
0

我有一個index.html文件,它在頁面打開時使用下面的JQuery將一頁菜單加載到div中。下面代碼中的監聽器可以處理我的index.html文件中的任何元素,但它們不能處理jquery腳本加載的文件中的元素。Jquery首先加載什麼

這裏是我的jQuery代碼

$(document).ready(function() { // this runs as soon as the page is ready (DOM is loaded) 

    $("#leftmenu") // selecting "div" (you can also select the element by its id or class like in css) 
     .load("http://www.maa.intranet.bae.co.uk/ma/Content/bus_serv/integrated_services/supply_chain_ss/information_assurance/leftmenu.html"); // load in the file specified 

    $("#content").load("WebContent/welcome.html"); 

    $("div.menuitem").hover(
      function() { 
       $(this).css({"background-color":"red"}); 
      }, 
      function() { 
       $(this).css({"background-color":"blue"}); 
      } 
     ); 


    $(".menulink").click(function(){ 
     alert("This is a test"); 
    }); 

}); 
+0

什麼是您的html?您可能想要使用.on(),因爲在.hover()執行時菜單項尚未加載。 – Tdelang

+0

看看接受答案的解決方案。這與您的情況類似,可能只是要求您更新處理事件的方式:http://stackoverflow.com/questions/17663154/can-not-trigger-any-javascript-events-inside-popover-in-引導/ 17663397 –

回答

1

試試這個

$(document).ready(function() { // this runs as soon as the page is ready (DOM is loaded) 

    $("#leftmenu") // selecting "div" (you can also select the element by its id or class like in css) 
     .load("http://www.maa.intranet.bae.co.uk/ma/Content/bus_serv/integrated_services/supply_chain_ss/information_assurance/leftmenu.html"); // load in the file specified 

    $("#content").load("WebContent/welcome.html"); 

    $("body").on('hover','div.menuitem', 
      function() { 
       $(this).css({"background-color":"red"}); 
      }, 
      function() { 
       $(this).css({"background-color":"blue"}); 
      } 
     ); 


    $("body").on('click','.menulink',function(){ 
     alert("This is a test"); 
    }); 

}); 

解釋:

未來元素 - 你不能重視他們的聽衆

所以你連接到一個更高的級別(在這種情況下爲「body」),然後點擊發生時 - 比較目標,調用。

p.s.我確定至少有5個重複的問題。

0

對於動態內容,請使用事件委託。嘗試把一些您的處理程序,即針對新加載的內容,下面的樣式語法:

$(document).on("click", "#selectorName", function() { 
    ^   ^
    ^   Selector action, could be hover, change, etc. 
    ^
    This is the container for the newly loaded elements, drill down as far as you can to this, in this case, we'll just use document. 
1

使用功能齊全,樓盤http://api.jquery.com/load/

這將是

$("#leftmenu") 
    .load("http://www.maa.intranet.bae.co.uk/ma/Content/bus_serv/integrated_services/supply_chain_ss/information_assurance/leftmenu.html") 
    .complete(function(// do event binding here) { 
}); 
0

使用http://api.jquery.com/on/

您這樣使用它:

$('ElementThatIsAlreadyThereAndWillStayThere') 
.on('click','#elementyouwantToBindTheEventTo', function(){ 
    //Handle "click" event here. 
}); 

您還可以使用其他事件,如.on('hover',...)