1

I'm new to jQuery and trying to work out how to achieve the following...

I have two div shown below, I want group div to show on load but not single div then onclick of group or single I need toggle between the two. How can this be done. This is what I have so far.

Send to: <a href="">Group</a> | <a href=""> Single<</a>

<div id="group">I'm a group</div>
<div id="single">I'm a single object</div>

UPDATE:

So something like this seems to work for me....

 $("#link").click(function(e) {
      e.preventDefault();
      $("#divA, #divB").toggle();
      $(this).text(function(i, text) { return (text == "Show viewA") ? "Show viewB" : "Show viewA" });
    });

but divB does not show.

4

4 回答 4

2

查看您的示例,我创建了一个简单的脚本,可以很好地满足您的需求。

<script>
  $(document).ready(function() {

    var $divA = $('#a'),
    $divB = $('#b'),
    $link = $('#link');
    $diplaytext = $('#display_text');

  // Initialize everything
  $link.text( 'Show Single' );
  $diplaytext.text( 'Group' );
  $divA.hide();

  $link.click(function(){

  // If A is visible when the link is clicked
  // you need to hide A and show B
  if( $divA.is( ':visible' ) ){
    $link.text( 'Show Single' );
    $diplaytext.text( 'Group' );
    $divA.hide();
    $divB.show();
  } else {
    $link.text( 'Show Group' );
    $diplaytext.text( 'Single Here' );
    $divA.show();
    $divB.hide();
  }

  return false;
  });


  });
</script>

然后...

display text: <span id="display_text"></span> | change: <a href="#" id="link" ></a>
<div id="a">a</div>
<div id="b">b</div>
于 2013-05-23T15:53:02.633 回答
2

只需将它们全部隐藏,然后取消隐藏刚刚单击的那个。

Send to: <a href="#" data-target="group" class="target">Group</a> | <a href="#" data-target="group" class="target">Single</a>

<div id="group" class="toggle">I'm a group</div>
<div id="single" class="toggle">I'm a single object</div>

然后使用这个jQuery:

$('.target').on('click', function(e) {
    e.preventDefault();
    $('.toggle').hide();
    $( '#' + $(this).data('target') ).show();
});
于 2013-05-23T15:26:15.013 回答
2

将您的代码更改为以下内容

Send to: <a data-div="group" href="#">Group</a> | <a data-div="single" href="#"> Single</a>

<div id="group">I'm a group</div>
<div id="single">I'm a single object</div>

<script>
    $(document).ready(function(){
        $("#single").css("display", "none");
        $("a").click(function(e){
            e.preventDefault(); // This prevents the link behaviour
            $("div").css("display", "none");
            $("#"+ $(this).attr("data-div")).css("display", "block");
        });

    });
</script>
于 2013-05-23T15:23:24.313 回答
1

div这是在两个元素之间切换的最佳方式:

$("#show_Blue").click(function(){
 $("#Blue").toggle();
 $("#Red").hide();
});

$("#show_Red").click(function(){
 $("#Red").toggle();
 $("#Blue").hide();
});

这里有一个演示

于 2014-08-16T10:33:09.407 回答