我的示例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/