簡體   English   中英

jQuery僅應用於一個元素

[英]jQuery only applied on one element

我的問題是我有一個議程,希望每個按鈕都具有相同的功能,但我擁有此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/

您不應該重復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按鈕更改為該類,它將起作用。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM