首先,給所有的圖像一個類(讓它叫picture
)和所有的名稱鏈接另一個(讓我們打電話給一個name
)。
//When a name is clicked.
$(".name").click(function() {
//Hide all the pictures.
$(".picture").hide();
//Get the name from the text of the link.
var name = $(this).text();
//Show the one with the right name.
$(".picture[src=" + name + ".jpg]").show();
}
如果你不想依靠鏈接文本和文件名(例如,如果他們不總是一致的),你可以使用自定義屬性,像data-name
,你可以在jQuery的訪問與.attr("data-name")
。
正如在評論中指出,也可能只是一個圖像(讓我們給它的ID picture
這段時間),並改變其src
屬性:
$(".name").click(function() {
//Get the name from the text of the link.
var name = $(this).text();
//Change the src attribute.
$("#picture").attr("src", name + ".png");
});
請注意,這第二種方法將不會加載頁面加載時的所有圖像。相反,它們只會在鏈接被點擊時加載。這可能是好的(如果有很多並且可能不需要它們),或者不好(如果用戶不得不等待它們是個問題)。你可以繞過preloading。
此外,如果您還想設置src
以外的其他屬性(如alt
),則使用第一種方法可能會更容易。
Disclaimar:我還沒有測試代碼。
但是,我認爲只使用一個'img'標籤並更改'src'屬性會更直截了當 – DelightedD0D
這個優點是當頁面加載時加載所有圖像,而不是當它們被顯示時(儘管如此,你也可以使用src方法強制JS)。此外,如果圖像具有其他屬性不同(如'alt'),它們也會自動交換。 – Anders
這是一個公平點:) – DelightedD0D