使用相应的onclicked图像更改图片标题?

时间:2015-12-16 17:05:18

标签: javascript jquery html image onclick

我制作了一个包含缩略图的图库页面,点击后,图像将显示在上面的主浏览器上(我已经工作了)。在主浏览器下,显示标题。但是我希望它能够根据图像改变标题,我可以添加到javascript和HTML中来实现这一目标吗?

E.g。单击缩略图1,图像查看器显示图像1,标题显示标题1.

然后单击缩略图2,图像查看器显示图像2,标题显示标题2等。

HTML

<div class="containermain">
<img id="img-main" alt="main image" src="images/placeholder.png" />

<div id="myCaption">Caption</div>

<div class="containerimg">
<img class="img" alt="thumbnail-image1" data-fullsize="images/image1.jpg" src="thumb/image1.jpg" />
<img class="img" alt="thumbnail-image2" data-fullsize="images/image2.jpg" src="thumb/image2.jpg" />
<img class="img" alt="thumbnail-image3" data-fullsize="images/image3.jpg" src="thumb/image3.jpg" />
<img class="img" alt="thumbnail-image4" data-fullsize="images/image4.jpg" src="thumb/image4.jpg" />
<img class="img" alt="thumbnail-image5" data-fullsize="images/image5.jpg" src="thumb/image5.jpg" />
</div>

的Javascript

$(document).ready( function() {
    $("img.img" ).on( "click", function( event ) {
        var newSrc= $(this).data("fullsize");          
        $("#img-main").attr("src", newSrc);
    });
});

2 个答案:

答案 0 :(得分:0)

使用此代码:

    $('img').click(function(){
        var alt = $(this).attr("alt")
        alert(alt)
    });

答案 1 :(得分:0)

您只需添加$('#myCaption').text($(this).attr("alt"))即可将点击图片的alt属性值分配给字幕文字。

$(document).ready( function() {
    $("img.img" ).on( "click", function( event ) {
        var newSrc= $(this).data("fullsize");          
        $("#img-main").attr("src", newSrc);
        $('#myCaption').text($(this).attr("alt"));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="containermain">
<img id="img-main" alt="main image" src="images/placeholder.png" />

<div id="myCaption">Caption</div>

<div class="containerimg">
<img class="img" alt="thumbnail-image1"  data-fullsize="images/image1.jpg" src="thumb/image1.jpg" />
<img class="img" alt="thumbnail-image2"  data-fullsize="images/image2.jpg" src="thumb/image2.jpg" />
<img class="img" alt="thumbnail-image3"  data-fullsize="images/image3.jpg" src="thumb/image3.jpg" />
<img class="img" alt="thumbnail-image4"  data-fullsize="images/image4.jpg" src="thumb/image4.jpg" />
<img class="img" alt="thumbnail-image5"  data-fullsize="images/image5.jpg" src="thumb/image5.jpg" />
</div>