【问题标题】:jQuery(window).load(function() breaks scriptjQuery(window).load(function() 中断脚本
【发布时间】:2015-03-30 23:05:03
【问题描述】:

我正在我正在处理的网站上实施 Isotope,但我在正确加载脚本时遇到了一些问题,尤其是在第一次访问时。

看来我必须为此使用 (window).load 函数,但如果我在我的 .js 文件中更改它,它会破坏 sctript 和功能。

下面的代码工作正常,除了它在第一次访问网站时不会加载。它还会导致 Firefox 中的一些布局问题

jQuery(function($) {

    var $container = $('#isotope-list'); //The ID for the list with all the blog     posts
    $container.isotope({ //Isotope options, 'item' matches the class in the PHP
        itemSelector: '.item',
        layoutMode: 'masonry'
    });

    //Add the class selected to the item that is clicked, and remove from the others
    var $optionSets = $('#filters'),
        $optionLinks = $optionSets.find('a');

    $optionLinks.click(function() {
        var $this = $(this);
        // don't proceed if already selected
        if ($this.hasClass('selected')) {
            return false;
        }
        var $optionSet = $this.parents('#filters');
        $optionSets.find('.selected').removeClass(
            'selected');
        $this.addClass('selected');

        //When an item is clicked, sort the items.
        var selector = $(this).attr('data-filter');
        $container.isotope({
            filter: selector
        });

        return false;
    });

});

如果我用下面的代码替换脚本的第一行,它会在第一次访问时加载,但过滤器功能被破坏。

jQuery(window).load(function()

它应该很容易修复,但我的 jQuery 知识非常有限。任何帮助深表感谢。

PS:网站使用 WordPress,所以 jQuery 处于非冲突模式。

【问题讨论】:

  • “看来我必须使用 (window).load 函数...” 为什么?你在什么地方读到过吗?
  • 是的,我在另一个关于如何实现同位素的教程中发现了这一点。但那个可能是错的......
  • 嗯,它应该不会有太大的区别,除了你上面的代码期望$ 将被传递给初始化函数。当您将该函数设置为“加载”事件处理程序时,不会发生这种情况,因此$ 将无法正确设置。

标签: javascript jquery wordpress


【解决方案1】:

不清楚为什么您的代码需要在“加载”事件处理程序中,但您需要将其添加为函数的第一行:

 var $ = window.jQuery;

否则,所有对 $ 的引用在用作“就绪”处理程序时由于传递给代码的参数而起作用,当它用作“加载”处理程序时将被破坏。

【讨论】:

  • 谢谢,这似乎在第一次加载时正确加载了脚本。添加加载事件处理程序后,所有样式都会在第一次加载/查看时正确加载,这在以前没有发生过。我仍然有一个小的样式问题,虽然它只发生在 Firefox 中,但这可能与这个脚本无关。
猜你喜欢
  • 2016-10-11
  • 2019-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 2020-09-24
  • 1970-01-01
相关资源
最近更新 更多