【问题标题】:What If document.ready won't work如果 document.ready 不起作用怎么办
【发布时间】:2014-03-06 14:54:32
【问题描述】:

每个 JavaScript 开发人员迟早都会遇到页面元素在 document.onready 事件中不可用的情况。发生这种情况是因为 onready 很快就会触发,尤其是当大多数页面部分动态加载(使用 AJAX)时。我现在使用 Drupal 7。 Drupal 不提供 Ajax 回调,看来需要编写自定义回调。

我的问题是:对于这种情况,最合适的解决方案是什么?

通常我会申请

jQuery(document).ready(function(){
               setTimeout(function tmr(){
               //Wait for any or task specific element will be available
                   if (jQuery('.bxslider').length) {
                            //Code here
                            do_code();
                   } else
                       setTimeout(tmr, 1000);
               }, 10);

或者更好地写一个回调?还是没有什么不同?

【问题讨论】:

  • 那你为什么不使用自定义回调呢???编辑:哎呀对不起,看起来这是你的问题。那么,使用回调是这里唯一有效的解决方案
  • 绝对不要投票,那太糟糕了。使用回调。
  • 如果我没记错的话,你可以在 div 上检查 onReady。你试过了吗?
  • @AlexBarac 不,你不能。所有准备好的 jquery 绑定事件都委托给文档,并且与任何元素内容无关
  • 最好的方法是使用回调。当然你可以轮询,但回调更优雅,而且更容易理解

标签: javascript jquery ajax drupal drupal-7


【解决方案1】:

像这样附加你的 js 行为:

Drupal.behaviors.nameOfYourModule= {
  attach: function (context, settings) {
    // your code here
  }
};

这样,您的代码将在每个请求(包括 AJAX 请求)上执行。

更多信息see this blog post on the subject.

【讨论】:

    猜你喜欢
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2013-10-01
    • 1970-01-01
    • 2018-01-20
    • 2010-11-09
    • 1970-01-01
    相关资源
    最近更新 更多