简体   繁体   中英

HTML JavaScript hide/show button

I'm working on a little Ruby on Rails application and I'm trying to add a hide/show button which hides a div with some Id. I've followed the steps from this post and it hides the content (second answer). The problem is that the content is not hidden permanently. Once I click in the button, the content dissapears, then the browser do something like an auto refresh and the content appears again.

Could anyone help me with this? It is my first application and my background in javascript is quite poor...

A piece of the code I want to hide/show is the following:

<div id='test'>
  <div class="col_4 patients-list">
    <!-- Patients list -->
    <h5>Patients en cours: <%= @patients.size %></h5>
    <div>
      <% @patients_anomaly.each do |patient| %>
        <div class="patient-anomaly"><%= link_to_patient patient %></div>
      <% end %>
      <% (@patients_to_exit - @patients_anomaly).each do |patient| %>
        <div class="patient-to-exit"><%= link_to_patient patient %></div>
      <% end %>
      <% @patients_normal.each do |patient| %>
        <div class="patient-normal"><%= link_to_patient patient %></div>
      <% end %>
    </div>
  </div>
</div>
<button>Click</button>

and the javascript of the button is:

<script type="text/javascript">
  $("button").click(function() {
    $("#test").toggle('hide');
  });
</script>

Thank you in advance.

I see that you tagged jQuery, did you try $('#element').hide() and $('#element').show() ?

Documentation for show , Documentation for hide

您可以将type="button"button因为默认行为是submit ,它submits页面,因此页面以default state

<button type="button">Click</button>

Instead of this <button>Click</button> , add this

= link_to 'Hide', 'javascript:void(0);', id: 'hideContent'

Then in Javascript

$('#hideContent').on('click', function(){
  $('#test').toggle('hide');
});

This won't reload your page.

Hope that helps!

<div id='test'></div>
<button id="hide_show">Click</button>
<script>
  $('#hide_show"').click(function(){
    $('#test').toggle();
  });
</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