简体   繁体   English

根据单击的文本更改图像源?

[英]Change image source depending on text clicked?

I want to set up a page that has the following:我想设置一个具有以下内容的页面:

Bob
Mary
Sue
Jane

<img src="none.jpg">
<img src="Bob.jpg">
<img src="Mary.jpg">
<img src="Sue.jpg">
<img src="Jane.jpg">

All of the images are initially invisible ( display: none; ), except none.jpg.所有图像最初都是不可见的( display: none; ),除了 none.jpg。 When Bob is clicked on, none should disappear, and Bob should become visible.当 Bob 被点击时,任何东西都不应该消失,而 Bob 应该变得可见。 What's the easiest way to go about this?解决这个问题的最简单方法是什么?

JavaScript/JQuery are what I'm trying to use. JavaScript/JQuery 是我想要使用的。 I've found methods that can toggle the display attribute, but it is clunky in that it requires me sending commands regarding ALL of the associated images.我找到了可以切换显示属性的方法,但它很笨拙,因为它需要我发送有关所有关联图像的命令。

I know the solution involves loading all of the images and then just changing their visibility, but changing the source will solve the problem stated above.我知道该解决方案涉及加载所有图像,然后仅更改其可见性,但更改源将解决上述问题。

First of all, give all the images a class (lets call it picture ) and all the name links another one (lets call that one name ).首先,给所有的图像一个类(我们称之为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();
}

If you don't want to rely on the link text and the file names (for instance, if they do not always match), you can use a custom attribute like data-name that you can access in jQuery with .attr("data-name") .如果您不想依赖链接文本和文件名(例如,如果它们不总是匹配),您可以使用自定义属性,如data-name ,您可以在 jQuery 中使用.attr("data-name")

As pointed out in comments, you could also have just one image (lets give it the id picture this time), and change its src attribute:正如评论中指出的,你也可以只有一张图片(这次让我们给它 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");
});

Please note that this second approach will not load all the images when the page loads.请注意,当页面加载时,第二种方法不会加载所有图像。 Instead they will only load when the link is clicked.相反,它们只会在点击链接时加载。 This can be good (if there are many and all of them might not be needed), or bad (if the user having to wait for them is a problem).这可以是好的(如果有很多并且可能不需要所有这些),也可以是坏的(如果用户不得不等待它们是一个问题)。 You can get around it by preloading .您可以通过预加载来绕过它。

Also, if you want to set other attributes than src as well (like alt ) it might be easier with the first approach.此外,如果您还想设置src以外的其他属性(如alt ),使用第一种方法可能会更容易。

Disclaimar: I have not tested the code.免责声明:我没有测试过代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM