javascript - 如何从特定元素获取图像src

标签 javascript jquery html css

我的示例html部分包含几个元素,如下所示:

<ul class="catalog">
  <li class="catalog_item catalog_item--default-view">
    <div class="catalog_item_image">
      <img src="/img/01.png" alt="model01" class="catalog_item_icons__big-foto">
   </div>
   <ul class="catalog_item_icons">
      <li class="catalog_item_icons__preview"><img src="/img/01-01.png" alt="01" class="catalog_item_icons__preview--foto-small"></li>
      <li class="catalog_item_icons__preview"><img src="/img/01-02.png" alt="02" class="catalog_item_icons__preview--foto-small"></li>
      <li class="catalog_item_icons__preview"><img src="/img/01-03.png" alt="03" class="catalog_item_icons__preview--foto-small"></li>
   </ul>

我想要 更改 img.catalog_item_icons__big-foto 的 src 和 img.catalog_item_icons__preview--foto-small 的 src

点击 li 元素后仅在其父元素 ul.catalog 中。

这是我的尝试:

$(".catalog_item_icons__preview").each(function () {
  $(this).on("click", function() {
    console.log('Clicked preview!');
    // get image fileName
    var smallImagePath = $(this).children("img").attr("src");
    console.log("small image: " + smallImagePath);
    var $bigPreview = $(this).closest('img.catalog_item_icons__big-foto').attr("src");

    // print in console src of nearest big image
    console.log($bigPreview);

  });

});

我可以获取小图像的src,但甚至无法读取树中上面img的src。 控制台输出:未定义。不明白为什么:(

最佳答案

使用此脚本:

$(document).ready(function() {
    //It is executing a function when it is clicked on an item
    $('.catalog_item_icons li').click(function() {
        //Taking the source of the image of the clicked element.
        //with $('img', this) you are choosing the the image in the clicked element
        _src = $('img', this).attr('src');
        //In the next line I am assigning to the _obj variable - the parent .catalog_item--default-view of the clicked element
        _obj = $(this).parents('.catalog_item--default-view');
        //In the next line i am changing the source attribute of the .catalog_item_icons__big-foto located in the _obj object
        $('.catalog_item_icons__big-foto', _obj).attr('src', _src);
    });
});

关于javascript - 如何从特定元素获取图像src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33478602/

相关文章:

javascript - 如何将可拖动元素放入特定位置

javascript - 单选按钮值和提交按钮

javascript - 为什么 React router v4 会做出错误的重定向?

javascript - 为什么 parseJSON 在服务器的以下响应中失败?

jQuery thickbox 窗口从窗口内单击调整大小

html - 为什么文本被推向圆圈的顶部

javascript - 如何使没有 href 属性的链接可访问?

javascript - 使用javascript在IE中设置cookie

javascript - 检查对象参数是否未定义

javascript - ng-app、ng-repeat、ng Controller 等……从 HTML DOM Angular 来看它们是什么以及 JS 如何访问它们?