2

我在一个 wordpress 网站上工作,我想在我的一个页面中使用 jQuery Masonry,但它不起作用。我搜索并尝试了许多更改,但没有结果。

我在这里:

在 header.php 我添加了这个:

    <?php wp_enqueue_script("jquery"); ?>

    <?php wp_head(); ?>

<script language="javascript" type="text/javascript" src="<?php bloginfo('template_url'); ?>/javascripts/jquery.masonry.min.js"></script>

<script language="javascript" type="text/javascript" src="<?php bloginfo('template_url'); ?>/javascripts/jquery.imagesloaded.js"></script>

<script language="javascript" type="text/javascript">

var $container = $('#masonry-list');
$container.imagesLoaded(function(){
  $container.masonry({
    itemSelector: '.masonry-item', isAnimated: true
  });
});

</script>

</head>

在模板文件(list-objects.php)中我有这个标记:

<div id="masonry-list">
    <h3> this-is-list-object-page </h3>


        <?php $loop = new WP_Query( array( 'post_type' => 'objects', 'posts_per_page' => -1 , 'orderby' => 'rand' ) ); ?>

    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> 


    <div class="masonry-item">
        <?php the_title( '<a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" rel="bookmark">', '</a>' ); ?>

        <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
   <?php the_post_thumbnail(); ?>
   </a>
        <?php echo get_the_term_list( $post->ID, 'place', 'مکان قرار گیری: ', ', ', '' ); ?>
        <?php echo get_the_term_list( $post->ID, 'category', 'رده: ', ', ', '' ); ?>
    </div>



<?php endwhile; ?>
</div>

我检查了所有 .js 文件是否已加载并且地址等没有问题。页面地址是:http://5.144.130.63/?page_id=69

有人可以帮我解决这个问题吗?

4

1 回答 1

2

You have at least two problems, possibly three:

  1. Your script is running before the page is fully loaded. You need to wrap it in the jQuery document ready function (example below)

  2. When using jQuery in WordPress, you need to reference it via the jQuery function - using the $ function will end up with "collisions" with other libraries.

  3. It appears that you are using both the imagesLoaded and masonry plugins - are you sure there is no collission between the two, causing issues? They both aim to position images after they are loaded - I'd encourage you to remove the imagesLoaded and see if you get what you want.

Alter your script like below, and you should see it work:

<script language="javascript" type="text/javascript">  
    // This line tells the script to run after the page is loaded,
    // As well as allows you to use the `$` function within the script
    jQuery(function($) {  
        $('#masonry-list').masonry({
            itemSelector: '.masonry-item', 
            isAnimated: true
        });
    });
</script>
于 2012-10-28T20:03:44.613 回答