【问题标题】:Can you choose what document to target in a $(document).ready() call?您可以选择 $(document).ready() 调用中的目标文档吗?
【发布时间】:2015-12-27 21:38:21
【问题描述】:

是否可以在$(document).ready(); 函数中选择要定位的页面?

类似

$('page1.html').ready();

提前致谢!

【问题讨论】:

标签: javascript jquery dom document


【解决方案1】:

这些是 jQuery 中常用的不同类型的 Document Ready 函数(又名 jQuery DOM Ready)。许多开发人员似乎在不知道为什么的情况下使用它们。因此,我将尝试解释为什么您可能会选择一个版本而不是另一个版本。将文档就绪函数想象成一个在页面元素加载后触发的自执行函数。

有关如何使用 Document Ready 函数的更多信息,请参阅在哪里声明 jQuery 函数。

文档就绪示例 1

$(document).ready(function() {
    //do jQuery stuff when DOM is ready
});

文档就绪示例 2

$(function(){ 
    //jQuery code here 
});

这相当于示例 1……它们的字面意思是相同的。

文档就绪示例 3

jQuery(document).ready(function($) {
    //do jQuery stuff when DOM is ready
});

添加 jQuery 有助于防止与其他 JS 框架发生冲突。

为什么会发生冲突? 冲突的发生通常是因为许多 JavaScript 库/框架使用相同的快捷方式 name 是美元符号 $。然后,如果它们具有相同的命名函数,则浏览器将获得 糊涂了!

我们如何防止冲突? 好吧,为了防止冲突,我建议给 jQuery 命名空间起别名(即使用上面的示例 3)。 然后当您调用 $.noConflict() 以避免命名空间困难时(因为 $ 快捷方式不再可用) 每次需要时,我们都强制它写 jQuery。

jQuery.noConflict(); // Reverts '$' variable back to other JS libraries
jQuery(document).ready( function(){ 
         //do jQuery stuff when DOM is ready with no conflicts
   });  

//or the self executing function way
 jQuery.noConflict();
 (function($) { 
    // code using $ as alias to jQuery
})(jQuery);

文档就绪示例 4

(function($) { 
    // code using $ as alias to jQuery
  $(function() {
    // more code using $ as alias to jQuery
  });
})(jQuery);
// other code using $ as an alias to the other library

这样你可以在一个函数中嵌入一个函数,同时使用 $ 作为 jQuery 别名。

文档就绪示例 5

$(window).load(function(){  
    //initialize after images are loaded  
});

有时您想操作图片,而使用 $(document).ready() 您将无法做到这一点 如果访问者尚未加载图像。在这种情况下,您需要初始化 图片加载完成时的jQuery对齐功能。

您也可以使用纯 JavaScript 并在 html 中附加一个调用 body 标记的函数,仅当您不使用 JS 框架时才使用它。

阅读更多:http://api.jquery.com/ready/

【讨论】:

  • @charlietfl 没有错,我已经试过了,你可以试试
  • 元素没有ready。如果在选择器存在之前调用代码,它将什么都不做。您误解了 ready 的作用,$(selector).ready() 没有有效的用例
  • 我删除它.,.但如果可以的话,我需要你尝试一下,然后告诉我什么以及如何
【解决方案2】:

只有documentready() 函数(当DOM 完全加载时执行的函数)。也就是说,您可以执行以下操作:

$(document).ready(function() {
    if ( document.location.pathname === '/page1.html' ) {
        // Some action
    }
});

【讨论】:

    【解决方案3】:

    你可以这样做。

    // same as $(document).ready() |$(document).on('ready) etc.
    $(function(){
        function loader(){
           var $element = $('Your Pointer to element');
           //If the number of elements matching the pointer is greater than 0
            if($element.length > 0) { 
               //its loaded
         }
         else {
             //since it isn't loaded , repeat in 250ms to see if it is
             setTimeout(function(){ loader(); }, 250); 
         }
     }
    

    这是一种方法。它不是一个完美的解决方案,因为您从不真正想要在脚本中设置 setTimeouts,但是由于我不知道您的其余代码在做什么,所以这将是我能提出的最佳建议。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      • 2015-05-26
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多