我认为这是一个非常新手的问题,所以感谢您帮助我学习。我正在尝试按照 here 的步骤实现客户端 Google Analytics 实验。
我一直这样使用 document.ready
$( document ).ready(function() {
// Handler for .ready() called.
});
这里的说明推荐这个(没有功能):
$(document).ready(
// Execute the chosen view
pageVariations[chosenVariation]
);
我想在实验之外的同一页面上调用一些其他函数,但是当我尝试将它们合并到一个 document.ready 中时,Google Analytics 实验将无法运行。所以我有两个问题:
什么时候可以不将 function 包含在 document.ready 中?查看文档 here ,我从未见过它是在没有功能的情况下编写的,所以我对此不清楚
将
pageVariations[chosenVariation]
添加到现有 document.ready 的正确方法是什么?我尝试将其添加到我的代码中,如下所示,但该实验仅在其位于其自己的单独 document.ready 内时才有效。<script> var chosenVariation = cxApi.chooseVariation(); var pageVariations = [ function() { console.log('variation one'); }, function() { document.getElementById('hero').src = 'heroB.jpg'; document.getElementById('oval').src = 'es_03b.jpg'; console.log('variation two'); } ]; $(document).ready(function () { pageVariations[chosenVariation]; about(); truck(); $("#vid").click(function() { $.fancybox({ autoSize: false, inline:true, height: 456, width: 700, href:"#cab" }); }); }); </script>
最佳答案
When is it OK not to include function with document.ready? Looking at the documentation here, I don't ever see it written without function so not I'm not clear on this
$(document).ready(function(){
// Something here
});
和
var a = function() {
// Something here
};
$(document).ready(a);
或
$(function(){
// something here
});
完全一样的东西。
简而言之,只要第一个参数是一个函数(无论是否引用),通过外部变量加载它就绝对没问题。
澄清一下:在第一种情况(和第三种情况)中,您使用匿名函数,而在第二种情况下,您通过变量引用函数。
根据您的情况,您正在做什么:
// Wait for the DOM to load, then execute the view for the chosen variation.
$(document).ready(
// Execute the chosen view
pageVariations[chosenVariation]
);
与第二点(带有变量 a 的点)基本相同,但是,您不是通过变量引用它,而是通过数组引用它。
接下来,关于您的第二点,由于您位于函数内部并且没有引用它,因此您应该执行该函数才能使其工作,因此,而不是:
$(document).ready(function(){
pageVariations[chosenVariation];
about();
truck();
$("#vid").click(function() {
$.fancybox({
autoSize: false,
inline:true,
height: 456,
width: 700,
href:"#cab"
});
});
});
替换:
pageVariations[chosenVariation];
与:
pageVariations[chosenVariation]();
编辑:
正如 Ted 上面所指出的,进行多个文档就绪调用也是完全可以的,因此,如果您遇到问题,也可以执行以下操作:
$(document).ready(
// Execute the chosen view
pageVariations[chosenVariation]
);
$(document).ready(function(){
// The rest of your code here
});
关于javascript - Document.ready 带/不带函数,并将数组添加到现有代码中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31030840/