【问题标题】:jQuery .delegate not working [closed]jQuery .delegate 不工作 [关闭]
【发布时间】:2013-05-08 16:30:56
【问题描述】:

以下代码可在页面加载时切换类,但在 Ajax 调用后不起作用。

html([field_map_location] 是 Drupal 令牌):

<div class="clearfix dir-map">
<a href="#" class="show">Map</a>
<div id="slidingDiv" class="outside">
[field_map_location]
</div>
</div>

javascript:

<script type="text/javascript">
 jQuery(function($) {
$(document).ready(function() {
    $('.dir-map').delegate('a', 'click', function(e) {
        e.preventDefault(); 
        $(this).next('div').toggleClass('outside inside');
    });
});

});
</script>

更新 我已经尝试了以下推荐的解决方案,但仍然无法正常工作。

<script type="text/javascript">
 jQuery(function($) {
    $(document).delegate('.dir-map a', 'click', function (e) {
        e.preventDefault(); 
        $(this).next('div').toggleClass('outside inside');
    });
});
</script>

抱歉,我是个菜鸟,所以我不知道如何向您展示 AJAX 调用的代码。我可以告诉你,这个 html 是 Drupal 视图的一部分,我正在使用它的 AJAX 功能。

【问题讨论】:

  • 显示使其无法工作的 Ajax 调用代码。
  • (不是你的问题的答案,但是)没有必要使用jQuery(function($) { $(document).ready(function () {}); }); - 你只是用一个准备好的处理程序包装一个准备好的处理程序。
  • Ajax 调用在哪里?它有什么变化?
  • 您确定.dir-map 元素是稳定不变的吗?您可能需要使用更高级别的容器
  • 至少为了验证尝试这个$(document).delegate('.dir-map a', 'click', function (e) { 可能在ajax 调用中你正在覆盖.dir-map

标签: javascript jquery drupal


【解决方案1】:

有时 Drupal 使用 AJAX 会很有趣;挂钩 Drupal 自己的 JS 行为系统可能会有所帮助...

(function($) {
  Drupal.behaviors.custom = {
    attach: function(context, settings) {
      $('.dir-map a', context).click(function (e) {
        e.preventDefault(); 
        $(this).next('div').toggleClass('outside inside');
      });
    }
  };
})(jQuery);

附加的有点过时的事件是因为 Drupal 7 仍然附带 jQuery 1.4.2。

【讨论】:

  • 谢谢!你很准。现在,我只需要自己学习如何做到这一点。
  • This link 将是无价的 :) (查找“Drupal.behaviors 实际示例”)
  • 感谢您的链接。这段代码在 jQuery 更新中会有问题吗?
  • 不应该,以上都兼容最新版的jQu​​ery,就是有点老派了
猜你喜欢
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 2017-06-17
  • 1970-01-01
  • 1970-01-01
  • 2013-01-28
  • 2012-11-13
相关资源
最近更新 更多