简体   繁体   中英

jQuery click to hide paragraphs beneath <h3> tags

I have a web page with fifteen sections. I want to be able to click the heading to each section and toggle the visibility of the "p" elements following their respective headings. Their visibility is set to "hide" on page start with this jQuery code:

$(function(){
    $("p").hide();
}

I am currently using fifteen separate event handlers to toggle visibility of the elements, each given its own ID:

$(function(){$("#show1").click(function(){
    $("#hidden1").toggle(400)});
});
$(function(){$("#show2").click(function(){
    $("#hidden2").toggle(400)});
});

etc. to "#show15". I am wondering if there is a more efficient way to do this. My code currently outputs what I need to achieve my objective, but in string form. I want to be able to execute the resultant string generated by my "for" loop.

var mySection = "";
var myString = "";
var SECT_MAX = 15;

for (var sectNum = 1; sectNum <= SECT_MAX; sectNum++) {
myString = "    $(function(){$(\"#show" + sectNum + "\").click(function(){\n           $(\"#hidden" + sectNum + "\").toggle(400)});\n    });\n";
mySection += myString;
};

// Display the code we have concatenated
console.log(mySection)

How do I pass the string to a jQuery function, in order to make each tag clickable to toggle visibility of its respective "p" paragraph?

You could add a common class to each header and attach a click handler on it. The handler will simply toggle the next() element :

 $('.header').on('click',function(){ $(this).next().toggle('slow'); }); 
 .header+p{ display: none; } .header{ cursor: pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h3 class="header">Header 1</h3> <p>Text</p> <h3 class="header">Header 2</h3> <p>Text</p> <h3 class="header">Header 3</h3> <p>Text</p> <h3 class="header">Header 4</h3> <p>Text</p> <h3 class="header">Header 5</h3> <p>Text</p> <h3 class="header">Header 6</h3> <p>Text</p> 

There certainly is a more efficient way of doing this, and that's by following the 'Don't Repeat Yourself' methodology.

To do that, you can use common classes on the h3 and the sibling p elements and using DOM traversal methods to relate the two when the heading is clicked, like this:

 $('.heading').click(function() { $(this).next('.para').toggle(400); }); 
 .heading { margin: 0; padding: 10px 0 3px; } .para { display: none; margin: 0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h3 class="heading">Title #1</h3> <p class="para">Lorem ipsum</p> <h3 class="heading">Title #2</h3> <p class="para">Lorem ipsum</p> <h3 class="heading">Title #3</h3> <p class="para">Lorem ipsum</p> 

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