jQuery-使用相同的类名分别显示/隐藏项目 [英] jQuery - Show/Hide items individually with same class name

查看:74
本文介绍了jQuery-使用相同的类名分别显示/隐藏项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jQuery的极端入门者.

I am an extreme noob with jQuery.

我正尝试根据相应链接显示一个项目,但不显示其他项目. 我所有的链接都具有相同的类名和跨度.

I'm trying to show an item based on it's corresponding link...without showing the other items. All my links have the same class name, as well as the spans.

我不知道这是否可以完成...我的脑袋花了太长时间了.

I don't know if this can be done or not...been racking my brain for too long on this one.

这是代码:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>jQuery - Show/Hide items individually with same class name</title>

<style type="text/css">
* { outline: none; }
a { display: inline-block; margin-right: 10px; float: left; text-decoration: none;     padding: 10px; }
span { text-align: center; display: inline; padding: 20px; background: blue; color: #fff; float: left; margin-right: 20px; width: 120px; }
div#wrap { float: left; clear: left; margin-top: 10px; }
div#linkOne, div#linkTwo, div#linkThree { background: #ccc; display: inline-block;     float: left; margin-right: 20px; }
</style>

<script type="text/javascript">

    $(document).ready(function(){

      var spans = $("span").each(function(j){ $(this).attr({class : "myDiv" + j}) });
      $(spans).hide();

      $(".show").each(function(i){
        $(this).attr({class : "show" + i});
        $(this).bind("click", function(e){
         $(spans).show();
       });
      });

      $(".hide").click(function(){
       $(spans).hide();  
      });

     });

</script>
</head>

<body>
  <div id="linkOne">
    <a class="show" href="#">Show1</a>
    <a class="hide" href="#">Hide1</a>
  </div>
  <div id="linkTwo">
    <a class="show" href="#">Show2</a>
    <a class="hide" href="#">Hide2</a>
  </div>
  <div id="linkThree">
    <a class="show" href="#">Show3</a>
    <a class="hide" href="#">Hide3</a>
  </div>

  <div id="wrap">
    <span class="myDiv">div1</span>
    <span class="myDiv">div2</span>
    <span class="myDiv">div3</span>
  </div>

</body>
</html>

推荐答案

尝试将链接div的另一个ID添加到您要打开的跨度中:

Try adding another id of the links div to the span you want to open:

更改 div1 到 div1

change div1 to div1

然后添加jQuery魔术:

Then add the jQuery magic:

$(function(){
    // First hide all hide links initially.
    $(".hide").hide();

    // then attach hide handler
    $(".hide").bind("click", function(){
        $(this).siblings(".show").show();
        $(this).hide();
        $(".myDiv." + $(this).attr("id")).show();
    });

    // and the show handler
    $(".show").bind("click", function(){
        $(this).siblings(".hide").show();
        $(this).hide();
        $(".myDiv." + $(this).attr("id")).hide();
    });
});

HTH 亚历克斯

这篇关于jQuery-使用相同的类名分别显示/隐藏项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆