2015-09-09 54 views
0

我有一個形象的畫廊像下面點擊一個圖片庫的圖像和獲取源

<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(可能是使用的警報(),以顯示SRC);這怎麼可能使用jQuery?

回答

1

$('img').on('click', function() {});針對DOM中的img元素,並向它們添加點擊事件函數。您可以使用.attr('src')$(this)來獲取屬性來源,其目標是您單擊的特定img來觸發事件功能。

$(document).ready(function() { 
 
    $('img').on('click', function() { 
 
    \t 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>

0

綁定click()事件處理程序,以獲取回調函數使用this.src內圖像源,這指的是被點擊的DOM對象

$(document).ready(function() { 
 
    $('img').on('click', function() { 
 
     alert(this.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>

相關問題