jQuery href navigation

jQuery href navigation

本文关键字:navigation href jQuery      更新时间:2023-09-26

我正在尝试制作一个简单的页面。 我只想一次显示一个部门并使用 href # 在正文中导航。 我想我需要根据单击的锚链接显示/隐藏。 谢谢。

.HTML

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="javascript.js"></script>
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
    <meta charset="utf-8">
</head>
<body>
    <div id="home">
        <a href="#" rel="test">Go To Testing Number</a>
    </div>
    <div id="test">
        <a href="#" rel="home">Home</a>
        <p>Testing Number</p>
        <input type="number" value="0" />
    </div>

</body>
</html>

JavaScript

$(document).ready(function(){
    $('div').not('#home').hide();   // show home page first
});
// this function needs to change I think, it does not work properly
$('a').on('click', function(){
   var target = $(this).attr('rel');
   $(target).hide();
   $("#"+target).show();
});
//this should work fine 
$('a').on('click', function(){
    var     target = $(this).attr('rel');
    If(target == "home"){
        $("#home" ).hide();
        $("#test").show();
    }else{
        $("#test" ).hide();
        $("#home").show();
    }
});

您正确显示了选定的 DIV,但用于隐藏其他 DIV 的代码是错误的。您为什么认为$(target)会选择已经显示的 DIV?

为不同选项卡的所有 DIV 提供相同的类,以便您可以在一次调用中隐藏它们。

<div id="test" class="tab">
    <a href="#" rel="home">Home</a>
    <p>Testing Number</p>
    <input type="number" value="0" />
</div>

那么jQuery将是:

$("a").click(function() {
    var target = $(this).attr("rel");
    $(".tab").hide();
    $("#" + target).show();
});

经过数小时的在线研究,我想通了。 简单而强大。

$(document).ready(function(){
    $('div').not('#home').hide();   // show home first
    $('a').click(function() {
        var target = $(this).attr('href');
        $('div').not(target).hide();
        $('div').filter(target).show();
    });
});

JSFiddle Solution