jQuery只应用于一个元素

jQuery only applied on one element

本文关键字:一个 元素 应用于 jQuery      更新时间:2023-09-26

我的问题是,我有一个议程,我希望每个按钮都有相同的功能。我有这个wordpress代码,但jQuery只适用于第一个按钮。我做了一把小提琴,你可以在这里看到: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/

您不应该重复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/

将id agendabutton更改为类,它就会工作。:)