gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:36:59 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com