jQuery仅应用于一个元素

时间:2014-10-15 09:51:00

标签: javascript jquery wordpress

我的问题是我有一个议程,我想在每个按钮上都有相同的功能我有这个wordpress代码,但jQuery只适用于第一个。我做了一个你可以在这里看到的jsfiddle:http://jsfiddle.net/m5nxkqcj/

的WordPress

<?php 

        $posts = get_field('agenda_relationship');

            if( $posts ): ?>

                    <?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>
                    <?php setup_postdata($post); ?>

                    <a id="agendabutton" class="large-12 small-12 columns"><?php the_title(); ?></a>

                    <?php if( have_rows('agenda') ): ?>

                                <?php while( have_rows('agenda') ): the_row(); ?>

                                    <div id="agendatext"><?php the_sub_field('start_time'); ?> - <?php the_sub_field('end_time'); ?> - <?php the_sub_field('agenda_description'); ?></div>

                                <?php endwhile; ?>

                            <?php endif; ?>


                    <?php endforeach; ?>
                <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
            <?php endif; ?>

现在我运行这个

的jQuery

jQuery(function($) {

$('#agendabutton').click(function() {
$('#agendatext').slideToggle(500);

})

});

但正如你在jsfiddle中看到的那样,只应用了一张幻灯片,是什么导致了这个以及如何使它工作? http://jsfiddle.net/m5nxkqcj/

2 个答案:

答案 0 :(得分:2)

您不应该复制ID,它们必须是唯一的。而是使用类来定位多个元素。

新HTML:

<a class="agendabutton" class="large-12 small-12 columns">Day one</a>
<div class="agendatext">08:00 - 9:15 - Her vil vi byde velkommen og spise lækker mogenmads buffet</div>

<a class="agendabutton" class="large-12 small-12 columns">Day Two</a>
<div class="agendatext">08:00 - 9:15 - Her vil vi byde velkommen og spise lækker mogenmads buffet</div>

Javascript代码也有一点变化。您不希望切换所有$('.agendatext'),只切换当前点击按钮后的一个。

$('.agendabutton').click(function () {
    // for this currently clicked .agendabutton toggle next .agendatext
    $(this).next('.agendatext').slideToggle();
});

演示:http://jsfiddle.net/m5nxkqcj/1/

答案 1 :(得分:0)

将ID agendabutton更改为该类,它将起作用。 :)