单击图像库的图像并获取源

时间:2015-09-09 17:47:11

标签: jquery

我有一个像下面这样的图片库

<div class="row gallery necklace">
    <div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
        <img id="jewellery1" class="FirstImage" src="./images/gallery/jewellery1.jpg">
    </div>
    <div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
        <img id="jewellery2" src="./images/gallery/jewellery2.jpg">
    </div>
    <div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
        <img id="jewellery3" src="./images/gallery/jewellery3.jpg">
    </div>
</div>

如果单击图像,我需要获取其src(可以使用alert()来显示src);怎么可能使用jquery?

1 个答案:

答案 0 :(得分:1)

$('img').on('click', function() {});定位DOM中的img元素,并添加点击事件功能。您可以使用.attr('src')获取属性来源,$(this)定位您点击的特定img以触发事件功能。

$(document).ready(function() {
    $('img').on('click', function() {
    	src = $(this).attr('src');
        alert(src);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row gallery necklace">
    <div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
        <img id="jewellery1" class="FirstImage" src="./images/gallery/jewellery1.jpg">
    </div>
    <div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
        <img id="jewellery2" src="./images/gallery/jewellery2.jpg">
    </div>
    <div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 gallery-box">
        <img id="jewellery3" src="./images/gallery/jewellery3.jpg">
    </div>
</div>