【问题标题】:Need help Showing one ID, hiding the rest需要帮助 显示一个 ID,隐藏其余 ID
【发布时间】:2014-07-14 18:43:38
【问题描述】:

我已经搜索并找到了这段代码,所以我想这是我应该使用的开始,但我真的不知道什么属性是错误的。

<script type="text/javascript">
$("a").click(function (){         
    $(".EventShowID").hide();            
    $("#" + $(this).attr("class")).show().siblings('EventShowID').hide();
});
</script>

链接 HTML:

<a href="#EventID1" class="EventID1">EVENT!</a>
<a href="#EventID3" class="EventID3">EVENT!</a>
<a href="#EventID4" class="EventID4">EVENT!</a>

分区:

<div id="EventShow">
    <div id="EventID1" class="EventShowID">Test Event #1<br>Testing adding an event for fun.</div>              
    <div id="EventID3" class="EventShowID">Test Event #2<br>Testing adding another event for fun.</div> 
    <div id="EventID4" class="EventShowID">Test Event #3<br>Testing adding anotheranother event for fun.</div>
</div>

怎么了。 :(

【问题讨论】:

  • 你试过.siblings('.EventShowID')吗?虽然你已经在上一行隐藏了它们,所以我不知道你为什么需要再次隐藏它们
  • 似乎在工作jsfiddle.net/BpYKn
  • 我想显示与我单击的链接相关的 DIV,并隐藏其余部分。 .siblings('.EventShowID') 没有任何区别:(
  • 你的 jQuery 链接是否正确?...

标签: javascript jquery html css hyperlink


【解决方案1】:

您没有将 click 事件处理程序包装在准备好的 jQuery 文档中,因此无法正确附加它(在页面加载之前,jQuery 不会找到任何元素)。

您的脚本应如下所示,并在您加载 jQuery 库后放置:

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        // When the document is ready.
        $(function () {
            // Hide all the elements. This could be replaced by a 
            // CSS rule.
            // ie: 
            // .EventShowID { display: none }
            $(".EventShowID").hide();

            // Attach the click event handler. Use "on" to guarantee it will be 
            // attached to any new element you add dynamically later on.
            $("a.EventToggle").on("click", function () {    
                // Hide all.     
                $(".EventShowID").hide();  

                // Show the element which id is equal the clicked element href.
                $($(this).attr("href")).show();
            });
        });
    </script>
</head>

Demo

【讨论】:

    【解决方案2】:

    您的代码需要更好的结构:

    <a href="#event-1" class="event-toggle">Event 1</a>
    <a href="#event-2" class="event-toggle">Event 2</a>
    
    <div class="event" id="event-1">1 here</div>
    <div class="event" id="event-2">2 here</div>
    

    jQuery:

    $('a.event-toggle').click(function(){
      $('.event').hide();
      var el = $(this).attr('href');
      $(el).show();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      相关资源
      最近更新 更多