需要帮助显示一个ID,隐藏其余ID

时间:2014-07-14 18:43:39

标签: javascript jquery html css hyperlink

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

<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的:

<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>

出了什么问题。 :(

2 个答案:

答案 0 :(得分:0)

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

<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();
});

答案 1 :(得分:0)

你没有把jQuery文档中的click事件处理程序包装好,所以它不能正确附加(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