gpt4 book ai didi

javascript - 在 `.attr()` 范围之外使用 jQuery `.each()` - 可能吗?

转载 作者:行者123 更新时间:2023-11-30 08:54:10 26 4
gpt4 key购买 nike

我想将具有类 .viewersrc 属性的第一个元素更改为其 data-src 属性的值。明显的代码不起作用:

$(".viewer").first().show().attr('src', $(this).attr('data-src'));

通过阅读关于 SO 的其他问题,我发现您必须这样做:

$(".viewer").first().show().each(function(){
$(this).attr('src', $(this).attr('data-src'));
});

它确实有效,而且我明白为什么(this 没有引用 .each 范围之外的元素)——但它看起来很奇怪在您已经使用 .first() 之后运行 .each()

有没有更简洁的方式来编写上面的代码?

最佳答案

将要重复使用的数据存储在变量中。

var viewer = $(".viewer").first().show();
viewer.attr('src', viewer.data('src'));

关于javascript - 在 `.attr()` 范围之外使用 jQuery `.each()` - 可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15169047/

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