[英]Trying to iterate through images & change src url within a div ID using jquery/javascript
Trying to iterate through all the images in a DIV class and change them out according to the landscape/portrait mode which detects from a function im not sure why it isnt working 尝试遍历DIV类中的所有图像并根据横向/纵向模式更改它们,横向/纵向模式从功能中检测到我不确定为什么它不起作用
for(var i = 0; i < $('#imgChange').children().length; i++){
var img = $('#imgChange').children[i];
// deviceOrientation - imageDimensions
// portrait-landscape, portrait-portrait, landscape-portrait, landscape-landscape
// img.children[i].attr('src','image' + i + '-' + orientationCheck() + '.png');
img.children[0].attr('src','image' + i + '-' + orientationCheck() + '.png');
}
}
Testing the first image. 测试第一个图像。 The rest havent been changed out yet 其余的都还没换
<div class="content" id="imgChange" custom-bg="1542111504805.png" >
<img src="image0-portrait.png"/>
</div>
</div><div class="slide">
<div class="content" id="imgChange" custom-bg="1542111396159.png" >
<img src="1542110991156.png"/>
</div>
</div><div class="slide">
<div class="content" id="imgChange" custom-bg="1542106085955.png" >
<img src="1542110993877.png"/>
</div>
</div><div class="slide">
<div class="content" custom-bg="1542106179480.png" >
<img src="1542110996555.png">
</div>
Your loop is going into children
twice, and the actual image is only one level deep. 您的循环会进入children
两次,并且实际图像只有一层深。 Also as @Ahmed Hammad points out, you can't have duplicate id
values on your elements - use a class instead. 同样,正如@Ahmed Hammad指出的那样,您的元素上不能有重复的id
值-请改用类。
for(var i = 0; i < $('.imgChange').length; i++){
var img = $('.imgChange')[i];
// deviceOrientation - imageDimensions
// portrait-landscape, portrait-portrait, landscape-portrait, landscape-landscape
// img.children[i].attr('src','image' + i + '-' + orientationCheck() + '.png');
$(img.children[0]).attr('src','image' + i + '-' + orientationCheck() + '.png');
}
Shorter way to write this is using attr(attributeName, function)
. 编写此内容的更简短方法是使用attr(attributeName, function)
。
Assumes you replace the duplicate id's and change to class instead 假设您替换了重复的ID并改为使用class
$('.imgChange img').attr('src', function(_,i){
return 'image' + i + '-' + orientationCheck() + '.png'
})
You don't need Jquery. 您不需要Jquery。 Remember ID attribute values should be unique. 请记住,ID属性值应该是唯一的。 You must not use id="imgChange"
more than once. 您不能id="imgChange"
使用id="imgChange"
。 Try this: 尝试这个:
let imgs = document.querySelectorAll('.imgChange img') for(i=0;i<imgs.length;i++){ img = imgs[i]; img.src = "https://www.gravatar.com/avatar/ea55d4ade339de113b9720c933546564?s=48&d=identicon&r=PG&f=1" //img.attr('src','image' + i + '-' + orientationCheck() + '.png'); }
.imgChange{ border: 1px solid red; }
<div class="imgChange"> <img/> <div/> <div class="imgChange"> <img/> <div/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.