0

我有一个 index.html 文件,它使用下面的 JQuery 在打开页面时将菜单页面加载到 div 中。下面代码中的侦听器可以处理我的 index.html 文件中的任何元素,但它们不能处理由 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");
    });

});
4

4 回答 4

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”),然后在发生点击时 - 比较并调用目标。

ps我确定至少有5个重复的问题。

于 2013-07-30T14:30:52.390 回答
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 ) {
});
于 2013-07-30T14:34:53.323 回答
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.
于 2013-07-30T14:31:13.240 回答
0

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

你像这样使用它:

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

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

于 2013-07-30T14:35:02.270 回答