【问题标题】:jQuery code optimization required for WordPress themeWordPress 主题需要 jQuery 代码优化
【发布时间】:2018-07-30 03:35:16
【问题描述】:

我正在尝试使用 jQuery 实现网格,就像基于此页面的 WordPress 主题中的 Google 图片一样,http://old.marcofolio.net/webdesign/browser_size_aware_content_scaling.html

google.load("jquery", "1.3.1");
google.setOnLoadCallback(function()
{
    // Detect browser resize and re-calculate
    $(window).bind("resize", calculateContent);

    // Calculate the content on load
    calculateContent();
});

/**
* Function that calculates on how the content should behave.
**/
function calculateContent( e ) {
    // Show all items in case they were hidden
    $("#content img").show();

    // Since we know the width each image takes (100px + 40px + 40px + 2px + 2px = 184px)
    // We can calculate how many rows are showed
    var imageWidth = 184;
    var contentAreaWidth = $("#content").width();
    var itemsPerRow = Math.floor(contentAreaWidth / imageWidth);

    // Retrieve the total number of images
    var totalNrOfItems = $("#content img").length;

    // Calculate how many full rows can be showed
    var fullRows = Math.floor(totalNrOfItems / itemsPerRow);

    // Calculate how many images fell off
    var itemsToHide = totalNrOfItems - fullRows * itemsPerRow;

    // Hide the images by counting backward (from the last item)
    for(var i = totalNrOfItems; i > totalNrOfItems - itemsToHide; i--) {
        // The "eq()" is zero-based, we'll need to substract one
        var remover = i - 1;
        $("#content img:eq("+remover+")").hide();
    }

    // Set debug information
    debug(itemsPerRow, itemsToHide);
}


/**
* Show debug information
**/
function debug(nritems, hidden) {
    $("#debug").html(
        "<p>Items per row: <strong>"+ nritems +"</strong>. Hidden images: <strong>"+ hidden +"</strong>.</p>"
    );
}

这是一个简单的函数,但我无法运行,因为它给了我很多错误,例如: 未捕获的 ReferenceError:未定义 google 在 script.js?ver=20170412:5

如何优化此 jQuery 代码以避免错误?

【问题讨论】:

    标签: wordpress grid


    【解决方案1】:

    未捕获的 ReferenceError: google 未定义在 script.js?ver=20170412:5

    这听起来像是您忘记在您的页面上包含/入队Google Loader's script。如果是这样,只需将其添加到主题的 function.php 文件中 - 例如:

    function wp2407_add_scripts() {
        // Rest of your scripts ...
        wp_enqueue_script( 'google-jsapi', 'https://www.google.com/jsapi' );     
    }
    add_action( 'wp_enqueue_scripts', 'wp2407_add_scripts' );
    

    【讨论】:

    猜你喜欢
    • 2014-07-02
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    相关资源
    最近更新 更多