gpt4 book ai didi

javascript - 按顺序获取数组值并为图像分配链接

转载 作者:行者123 更新时间:2023-11-28 16:55:31 24 4
gpt4 key购买 nike

你好,我有一些 HTML block

<div class="feed_name"><img height="50">      
<div class="feed_name"><img height="50">
<div class="feed_name"><img height="50">
<div class="feed_name"><img height="50">

和一些代码js

    var images = ["50.jpg","51.jpg","52.jpg","53.jpg","54.jpg","55.jpg","56.jpg","57.jpg","58.jpg","59.jpg","60.jpg","61.jpg","62.jpg","63.jpg","64.jpg","65.jpg","66.jpg","67.jpg","68.jpg","69.jpg","70.jpg","71.jpg","72.jpg","73.jpg","74.jpg","75.jpg","76.jpg","77.jpg","78.jpg","79.jpg","80.jpg","81.jpg","82.jpg","83.jpg","84.jpg","85.jpg","86.jpg","87.jpg","88.jpg","89.jpg","90.jpg"];
var target = document.getElementsByTagName('img');
var returnImages = [];
var currentImages;
function getUnique(count) {
// Make a copy of the array
var tmp = images.slice(images);
var ret = [];

for (var i = 0; i < count; i++) {
var index = Math.floor(Math.random() * tmp.length);
var removed = tmp.splice(index, 1);
// Since we are only removing one element
ret.push('img/users/' + removed[0]);
$(".feed_name img").each(
$(".feed_name img").attr("src", ret[i])
);

}
return ret;

}

returnImages.push(getUnique(6));
console.log(returnImages);

我想让所有图像都以数组 returnImage 的形式不同,但不知道怎么做,请帮助

最佳答案

我的 VanillaJS 尝试

/* a simple Array shuffler helper */
var shuffle = function(array) {
var a = array.slice(0);
a.sort(() => Math.random() - 0.5);
return a;
}

/* retrieve all the nodes of the images */
var imagesNode = document.querySelectorAll('.feed_name img');

/* fill an array of integers [50,...,90] */
var imagesUrl = Array(41).fill(0).map((i, j) => j + 50);

/* shuffle the array, limit the length of the array to the length
* of the nodes and - if you need it - sort() it again
*/
var imagesPicked = shuffle(imagesUrl).slice(0, imagesNode.length).sort();

/* set images url */
[...imagesNode].map((node) => {
var num = imagesPicked.shift();
node.src = num + '.jpg';
node.title = "this is the image number " + num;
});
<body>
<div class="feed_name"><img /></div>
<div class="feed_name"><img /></div>
<div class="feed_name"><img /></div>
<div class="feed_name"><img /></div>
</body>

关于javascript - 按顺序获取数组值并为图像分配链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57143268/

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