获取特定被单击图像的路径

Get the path of the particular clicked image

本文关键字:图像 路径 单击 获取      更新时间:2023-09-26

演示在这里

当我点击任意图像时,我想要得到该图像的路径。这里的问题是每次只给出图像1的路径。

同时,有了这个新的src,我想在id= cropimage

的图像中添加src
$(".img").click(function() {
    var newsrc = $(".img").attr("src");
    alert(newsrc);
});

在click事件处理程序中使用 $(this) 来获取被单击的元素。事件处理程序中的$(this)是发生事件的元素。

如果使用$('.img'),它将选择所有具有img类的元素,当对其使用attr时,它将返回第一个匹配的选择器的属性值。

$(".img").click(function() {
  var newsrc = $(this).attr("src");
  $('#cropimage').attr('src', newsrc);
  // Even Shorter Form
  // $('#cropimage').attr('src', $(this).attr('src'));
});
#cropimage {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<img class="img" src="http://www.w3schools.com/images/w3schools.png" />
<br/>
<img class="img" src="https://www.google.co.in/images/icons/hpcg/ribbon-black_68.png" />
<div id="img-container">
  <img src="" id="cropimage" />
</div>

请点击这个链接Js,它会帮助你的。

$( ".img" ).click(function() {
  var newsrc=$(this).attr("src");
    //alert(newsrc);
    $( "#cropimage" ).attr("src",newsrc);
});