문제

Im trying to make a dynamic jQuery function with some help from Advanced Custom Fields in Wordpress. This may not have something to do with the question, but I work in Wordpress with this plugin, anyway.

My code is like this:

<div id="restaurangmeny">

<h2>Vår meny</h2>

<? if( get_field('meny_for_restaurangen') ): ?>
<?php while( has_sub_field('meny_for_restaurangen') ): ?>

<div class="kategori">

<div class="kategorinamn" id="<?php the_sub_field('namn_for_kategorin'); ?>"><?php the_sub_field('namn_for_kategorin'); ?></div>

<div class="matratter" id="<?php the_sub_field('namn_for_kategorin'); ?>">

<? if( get_sub_field('matratter') ): ?>
<?php while( has_sub_field('matratter') ): ?>

<div class="matratt">

<div class="left">
<div class="namn"><?php the_sub_field('namn_pa_matratt'); ?></div>
<div class="beskrivning"><?php the_sub_field('beskrivning_av_matratten'); ?></div>
</div>

<div class="pris"><?php the_sub_field('pris_pa_matratten'); ?>:-</div>

</div>

<?php endwhile; ?>
<?php endif; ?>

</div>

</div>

<?php endwhile; ?>
<?php endif; ?>

</div><!--#restaurangmeny-->

So what I want is when I click on the div called "kategorinamn" I want to div called "matratter" be shown or hidden. That's why I use same id for "kategorinamn" and "matratter" just because these 2 belong together.

Simply, if I click on 1 I want everything that got the same id (1) be shown. If I click on 2 I want everything that got the same id (2) be shown.

I don't know what dynamic jQuery like this is called, but I'm far away from being good with jQuery so that's why I'm asking.

Something like this http://jsfiddle.net/gwK6d/18/, but with jQuery only and that fit's my code above.

도움이 되었습니까?

해결책

1) Import jquery

2) Make sure you are not using the same id for multiple elements

3) Change this bit:

<div class="kategorinamn" id="<?php the_sub_field('namn_for_kategorin'); ?>"><?php the_sub_field('namn_for_kategorin'); ?></div>
<div class="matratter" id="<?php the_sub_field('namn_for_kategorin'); ?>">

To this:

<div class="kategorinamn" id="<?php the_sub_field('namn_for_kategorin'); ?>">
    <?php the_sub_field('namn_for_kategorin'); ?>
    <div class="matratter" id="<?php the_sub_field('namn_for_kategorin'); ?>">
</div>

4) Declare this function after load:

$(".kategorinamn").click(function(){
    $(this).children('.matratter').toggle();
});

JSFIDDLE: http://jsfiddle.net/uRpc8/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top