您的代码有两个主要问题:
- 您不会将 jQuery 代码挂接到“文档就绪”事件。不这样做会(可能)导致它在文档完全加载之前运行,这在大多数情况下是不可取的。
- 您正在使用
onclick
内联 JavaScript。不要那样做。这不再是编写 JavaScript/HTML 集成的方式了。jQuery 有事件处理程序来为你捕捉点击事件。始终保持 HTML 和 JavaScript 100% 分开。
CSS:
.hidden {
display: none;
}
HTML
<p><a class="reveal" href="#hidden3">Edit</a></p>
<div id="hidden3" class="hidden step">
JavaScript
// $() is short for $(document).ready()
$(function () {
// hide all the steps on document load
$("div.step").addClass("hidden");
// show the one step that is identified by the current hash (if any)
$(document.location.hash).removeClass("hidden");
$("a.reveal").click(function (event) {
var idToReveal = $(this).attr("href");
// store the ID to show in the URL for bookmarking
document.location.hash = idToReveal;
// hide every step that is currently visible
$("div.step").not(".hidden").addClass("hidden");
// reveal the next div (as identified by the current link's href)
$(idToReveal).removeClass("hidden");
// prevent the default click behavior (i.e. prevent navigation)
event.preventDefault();
});
});
上面利用了一个事实document.location.hash
,一个页面内部<a href>
和jQuery 的 ID 选择器都使用相同的语法。
只要您只想在散列中传输一点信息,这就是您所需要的。