看起來你已經得到了需要清理一些誤解。 不要擔心你明確的正確軌道。
首先,您需要將您的調用包裝在一個document.ready事件中,像這樣。
<script type="text/javascript">
$(document).ready(function() {
var buttons = $("#buttons").find("a");
$("buttons").click(function() {
var id = $(this).attr("id");
$("pages id").css("display", "none");
$("pages id:eq("+id+")").css("display", "block");
});
});
</script>
這樣做的原因是因爲你的HTML依次呈現,也就是說,它逐行讀取它。當你的JavaScript代碼執行時,按鈕的HTML還沒有呈現,所以它不知道你在說什麼。還要注意,ready事件處理程序的構造幾乎與click事件處理程序相同。你只是在不同的對象上操作,並使用不同的事件。
下一個問題是,你似乎在努力如何選擇工作。
var buttons = $("#buttons").find("a");
你實際使用選擇這裏。 $()和.find()幾乎完全相同。然而,jQuery對象選擇器用於查詢整個文檔,find用於查詢子集。因此,對於你想要做的事情來說,這樣做更合適:
var buttons = $("a");
這只是說「選擇所有錨標籤」。當選擇器不是以特殊字符開始時,它只是尋找這種類型的標籤。 #字符用id和。查詢所有元素。字符查詢該類的所有元素。所以你的第一個陳述實際上是查詢任何不存在的id爲「按鈕」的元素。
最後,你不需要爲你想要做的事情創建一個var,所以爲了簡單起見,我們將擺脫那條線並轉到click處理程序。
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var id = $(this).attribute("id");
$("pages id").css("display", "none");
$("pages id:eq("+id+")").css("display", "block");
});
});
</script>
下一個問題是,你正在使用的ID屬性作爲數據字段。不要這樣做。如果您需要在其標籤內存儲有關元素的信息,請使用以「data-」開頭的自定義屬性。所以在這種情況下,我們可以改變你的錨標籤。
<div id="buttons">
<a href="#" data-id="0" class="mybutton myred">Div 1</a>
<a href="#" data-id="1" class="mybutton myblue">Div 2</a>
<a href="#" data-id="2" class="mybutton myblue">Div 3</a>
</div>
這稍微好一點。現在我們在div上也遇到了同樣的問題。我們可以做同樣的事情,但因爲我們要查詢這些信息,並且在類上使用選擇器要容易得多,所以我們只需根據id給予divs類。
<div id="pages">
<div class="mydivshow div1">1111</div>
<div class="mydivhide div2">2222</div>
<div class="mydivhide div3">3333</div>
</div>
現在我們可以回到jQuery並更改代碼。
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var id = $(this).attribute("data-id"); // Using a custom attribute.
$("#pages div").hide(); // gather all the div tags under the element with the id pages and hide them.
$(".div" + id).show(); // Show the div with the class of .divX where X is the number stored in the data-id of the object that was clicked.
});
});
</script>
而且應該這樣做!
我沒有完全讀你的答案,但它確實值得+1。 – undefined