首先,给所有的图像一个类(让它叫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