【问题标题】:jQuery event not working after load加载后jQuery事件不起作用
【发布时间】:2012-06-28 08:25:19
【问题描述】:
$(document).ready(function(){

$(function() {
    $('a.ajaxload').click(function(e) {           
      var url = $(this).attr('href');
      $('#desktopcontainer').load(url); // load the html response into a DOM element
      e.preventDefault(); // stop the browser from following the link
    });
});

$(function() {
    $(".accordion .accordion-tabs .tab").each(function(){
        $(this).click(function(){
            if ($(this).hasClass('tab')){
            $(this).removeClass('tab');
            $(this).addClass('active');
          }else{
            $(this).removeClass('active');
                    $(this).addClass('tab');
          }

          $(this).next().slideToggle('slow');
                return false;
        });
    });
});
});

我的标签工作正常,但是在我单击“a.ajaxload”向页面添加内容后,我的标签不再响应。

谁能告诉我问题出在哪里?

解决了!!!

我所做的是在加载后添加函数……看看下面的新代码,看看有什么不同。我希望它可以帮助某人。

$(document).ready(function(){

initDashboard();

$(function() {
    $('a.ajaxload').click(function(e) {           
      var url = $(this).attr('href');
      $('#desktopcontainer').load(url); // load the html response into a DOM element
      e.preventDefault(); // stop the browser from following the link
      initDashboard();
    });
});

function initDashboard() {
    $(".accordion .accordion-tabs .tab").each(function(){
        $(this).click(function(){
            if ($(this).hasClass('tab')){
            $(this).removeClass('tab');
            $(this).addClass('active');
          }else{
            $(this).removeClass('active');
                    $(this).addClass('tab');
          }

          $(this).next().slideToggle('slow');
                return false;
        });
    });
}

});

【问题讨论】:

  • 能否给我们看看你的html代码?
  • 也许点击也应该是live(注意:在jQuery 1.7+中你应该使用on代替)?它加载什么内容?你能发布一个jsfiddle>
  • @Phenix 我的 HTML 在页面中,我通过 load(url) 动态获取它们。
  • @Darhazar on() 对我不起作用,我是最新版本的 jQuery。

标签: jquery


【解决方案1】:

您需要on(),因为它是动态添加的(例如通过load 方法插入):

$('.accordion .accordion-tabs').on('click', '.tab', function(){
   if ($(this).hasClass('tab')) {
        $(this).removeClass('tab');
        $(this).addClass('active');
   }else{
        $(this).removeClass('active');
        $(this).addClass('tab');
   }

   $(this).next().slideToggle('slow');
        return false;    
   });
});

也不需要使用 jQuery 就绪处理程序三次,只需将所有与 jQuery 相关的代码放入此:

$(document).ready(function(){

});

文档:

【讨论】:

  • on() 似乎没有做任何事情——即使用户第一次访问该页面时也没有。这就是我首先使用 live() 的原因。有什么原因吗?
  • @Shina:它是最新的 jQuery 版本的一部分,尝试使用它的最新版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多