【问题标题】:Jquery doesn't work on DOM changeJquery 不适用于 DOM 更改
【发布时间】:2018-06-02 02:01:30
【问题描述】:

在这个多日节日的页面中

https://www.metropub.net/www.italiajazz.it/calendario-festival

我添加了以下JS

https://www.metropub.net/www.italiajazz.it/sites/default/files/js_injector/js_injector_5.js

jQuery( document ).ready(function() 
{
   console.log( "ready!" );
   jQuery('.fc-event-hori').on('mouseenter', function()
        {   
            x = jQuery(this).text();
            jQuery("a.fc-event-hori:contains('" + x + "')").css("background", "#fccd45"); 
            console.log('in');
        });
    jQuery('.fc-event-hori').on('mouseleave', function()
        { 
            x = jQuery(this).text();
            jQuery("a.fc-event-hori:contains('" + x + "')").css("background", "#15242a"); 
            console.log('out');
        });
});

用于将鼠标悬停延长到超过一周的节日。

它适用于第一页,但是当我更改月份时,它不再起作用了。

在不同的线程上寻找解决方案,例如这个链接

jQuery selector doesn't update after dynamically adding new elements

我修改了实现“委托事件处理”的原始代码,但我的代码仍然只在第一页有效。

我是否错过了其他东西?

【问题讨论】:

  • 请阅读MCVE
  • 尝试在事件中使用 $(document)
  • jQuery(document).on('.fc-event-hori', 'mouseenter', function() {
  • @LouysPatriceBessette:有JS的链接,不行吗?我想在我的问题中减少混乱:(。对不起我的误解......
  • @SanjayKumar:我试过你的解决方案,但它在第一页也不起作用:D

标签: jquery delegates


【解决方案1】:

我通过使用 delegation 解决了您的问题,就像 cmets 中建议的 Sanjay Kumar

但是,奇怪的是......您似乎对mouseentermouseover 事件有另一个问题。我认为他们可能在某处被阻止。我不能说。

我使用了mousemove 事件使其工作。

我直接在控制台中执行此操作。首先,我分离了您拥有的事件处理程序:

jQuery('.fc-event-hori').off('mouseenter');
jQuery('.fc-event-hori').off('mouseleave');
jQuery('.fc-event-hori').off('mouseover');

然后我输入了这个处理程序代码:

jQuery('.fullcalendar').on('mousemove mouseleave','.fc-event-inner', function(e){
  // Get the text.
  var x = jQuery(this).find('.fc-event-title').text();
  console.log(e.type);

  // Depending on the event, choose a color.
  if(e.type=="mousemove"){
    color="#fccd45";
  }else{
    color="#15242a";
  }

  // Use the text to lookup for the matching elements.
  jQuery(".fc-event-inner:contains("+x+")").css("background",color); 
});

而且效果很好。

现在,如果我是你,我会尝试查找是否有 .preventDefault() somewere 应用于这些事件......可能不是这样......但我会看看。我会使用Agent Ransak 搜索所有文件。

然后,我会考虑升级 jQuery 版本。您目前使用的是 1.7.2,在我看来这已经很老了。有guides帮助升级。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多