简体   繁体   中英

show and hide content on click

I have an html page and I want to show and hide content on button click.

HTML:

<div class="wpb_wrapper">

  <p>
    <button class="learn-more">Learn More</button>
    <button class="learn-more">Learn More</button>
    <button class="learn-more">Learn More</button>
    <button class="learn-more">Learn More</button>
 </p>

<p class="hide_paragraph" id="p1" style="display: none;">First paragraph</p>
<p class="hide_paragraph" id="p2" style="display: none;">Second paragraph</p>
<p class="hide_paragraph" id="p3" style="display: none;">Third paragraph</p>
<p class="hide_paragraph" id="p4" style="display: none;">Fourth paragraph</p>

        </div>

Also my function

$(document).ready(function () {
$('.wpb_wrapper p .learn-more').click(function(){

    $('.wpb_wrapper p .hide_paragraph').hide();
    $('#' + $(this).attr('paragraph_id')).show();

});

});

But it doesn't work

There is no attribute called paragraph_id in your button tags, so your $(this).attr('paragraph_id') returns undefined . Since paragraph_id is not a standard HTML attribute, I advise against simply adding it. Instead just add to each button a data-attribute like so:

<button class="learn-more" data-paragraph-id="#p1">Learn More</button>

and in your handler use $(this).data('paragraph-id') to identify the paragraph to be shown.

Notice that the hash sign is included so you don't have to use the string concatenation anymore. Simply call:

$($(this).data('paragraph-id')).show();
$(document).ready(function () {
 $('elem').click(function(){
  var getIndex = $('elem').index(this);
  $('elem2').hide();
  $('elem2:eq"' + getIndex + '"').show();
 });
});

Should work, hope it is exactly what you want :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM