简体   繁体   中英

Iterating through array in Rails as separate jQuery objects

I am iterating through an array in Rails to show a set of articles. I'd like a button to slide Toggle the article open when clicked (so each would be a headline and button, and the text would be revealed on button click).

The array looks like:

  <% @articles.each do |article| %>
  <div class="article_header">
    <h1><%= article.title %></h1>
    <button id="clickme" type="button">Show More!</button>
 <div class="article_content">    
          <p><%= markdown article.content %></p>
   </div>
      <% end %>
</div>

I am then trying to toggle the article_content with the following:

<script>
$( ".article_content" ).hide()
$( "#clickme" ).click(function() {
  $( ".article_content" ).slideToggle( "300", function() {
  });
});
</script>

After reading some other questions, I believe the issue is that article_content is a class, which is why currently the button opens and collapses all of the content text.

If I am iterating through an array, can I assign different IDs to target as my object so clicking the button for Article 1 opens and closes Article 1 only?

Unless you have a specific reason to assign the id to the button, then set a class on the button and then you can use .next() to achieve what you want.

jquery:

$(".clickme").click(function() {
  $(this).next(".article_content").slideToggle("300", function() {});
});

Html: change id="clickme" to class="clickme"

This will allow you to toggle multiple elements the way you want.

Demo below

 $(".article_content").hide() $(".clickme").click(function() { $(this).next(".article_content").slideToggle("300", function() {}); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="article_header"> <h1> article 1 </h1> <button class="clickme" type="button">Show More!</button> <div class="article_content"> <p> content 1 </p> </div> </div> <div class="article_header"> <h1> article 2 </h1> <button class="clickme" type="button">Show More!</button> <div class="article_content"> <p> content 2 </p> </div> </div> 

Make the button selector also a class:

<button class="clickme" type="button">Show More!</button>

Then try to find the nearest article_content of that button. The jQuery portion would look something like this:

<script>
  $( ".article_content" ).hide()
  $( "button.clickme" ).click(function() {
    $(this).siblings( ".article_content" ).slideToggle( "300", function({});
  });
</script>

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