每个 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);
或者更好地写一个回调?或者根本没有什么不同?
最佳答案
附加你的 js 行为,如下所示:
Drupal.behaviors.nameOfYourModule= {
attach: function (context, settings) {
// your code here
}
};
这样您的代码将在每个请求(包括 AJAX 请求)上执行。
关于javascript - 如果 document.ready 不起作用怎么办,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22228023/