gpt4 book ai didi

javascript - 访问子属性值

转载 作者:行者123 更新时间:2023-11-28 18:54:40 24 4
gpt4 key购买 nike

在 View 页面内,我有几个 id 以 my- 前缀开头的 div,

<div id="my-div1"><img src="/img/1.jpg" /></div>
<div id="my-div2"><img src="/img/2.jpg" /></div>
<div id="my-div3"><img src="/img/3.jpg" /></div>

在 js 代码中,我正在迭代每个元素,并且我想应用某些函数子 img 元素,在本例中为 backstretch

$(document).ready(function () {
$('div[id^="my-"]').each(function () {
$(this).css("background-size", "100% 100%");
$(this).css("background-repeat", "no-repeat");
// this doesn't work
$(this).children("img").backstretch($(this).attr('src'));
})
});

当我测试 $(this).children("img").length 返回每个 div 下的实际 img 数量,但我不知道如何将其 src 属性值传递给 backstretch 函数?

最佳答案

基于the documentation ,看起来 backstretch 不支持传入函数(jQuery setter 函数可能会这样做),所以你只能使用 each 。 :

$(this).children("img").each(function() {
$(this).backstretch(this.src);
});

请注意,我不打算使用 jQuery 来访问 src,那里已经有一个 DOM 属性准备就绪并正在等待。 :-)

或者,如果您想将 backstretch 应用于 div,因为每个 div 只有一张图像,您可以这样做:

$(this).backstretch($(this).find("img").attr("src"));

attr 将返回 div 中第一个图像的 src

最后,由于 backstretch 支持将多个图像作为幻灯片放映,如果您的 div 将有多个图像,您可以使用 children("img").map(...).get() 获取其 src 的数组属性:

$(this).backstretch($(this).children("img").map(function() {
return this.src;
}).get());

关于javascript - 访问子属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33844445/

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