jquery show hide replace area

六月ゝ 毕业季﹏ 提交于 2020-01-03 03:40:22

问题


how can i use jQuery to show/hide the same div area... essentially swapping out content?

here is what i have so far, and i cant figure out how to hide the previous content and replace it with the new content:

       <script type="text/javascript">
    $(document).ready(function(){

    $('.content').hide();

    $('a').click(function(){
    $('.content').show('slow');
    });

    //then hide previous content

    });

    </script>

<a href="#" id="a-link">A</a>
<a href="#" id="b-link">B</a>

  <div class="start-content" id="a">
  content here
  </div>

  <div class="content" id="b">
  content here
  </div>

回答1:


If you wrap the contents in a div, this would be a bit easier, like this:

<div id="wrap">
  <div class="start-content" id="a">
  content here
  </div>

  <div class="content" id="b">
  content here
  </div>
</div>

And this in jQuery:

$('a').click(function(){
  $("#wrap > div").hide(); //hide previous
  $('.content').show('slow'); //show what's clicked on
});

Since you have a convention with your IDs though, you can use that, either give you links a class, or wrap them as well, like this:

<div id="links">
  <a href="#" id="a-link">A</a>
  <a href="#" id="b-link">B</a>
</div>
<div id="wrap">
  <div class="start-content" id="a">
  content here
  </div>    
  <div class="content" id="b">
  content here
  </div>
</div>

Then you could use a single event handler for all your links like this:

$('#wap > div:not(.start-content)').hide(); //Initial hide
$("#links a").click(function() {
  $("#wrap > div").hide(); //hide previous
  var id = $(this).attr("id").replace('-link', ''); //matching id
  $('#' + id).show('slow'); //show what's clicked on
});



回答2:


Keep the content div visible; instead, just swap out the HTML content with $('.content').html(strvalue);



来源:https://stackoverflow.com/questions/2546342/jquery-show-hide-replace-area

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!