gpt4 book ai didi

php - 使用 javascript 从 xml 文件加载一系列随机图像

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

这是我目前拥有的代码,目前使用 javascript 根据需要从 xml 文件加载信息。我已将它设置为循环 4 次以选择 4 个图像,但这些显然只是 xml 文件中的前 4 个。

有谁知道从 xml 文件中随机选择 4 个无重复图像的最佳方法。

<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","include/photoLibrary.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

var x=xmlDoc.getElementsByTagName("photo");
for (i=0; i<4; i++)
{
document.write('<a href="');
document.write(x[i].getElementsByTagName('path')[0].childNodes[0].nodeValue);
document.write('" class="lytebox" data-lyte-options="group:vacation" data-title="');
document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
document.write('"><img src="');
document.write(x[i].getElementsByTagName('thumb')[0].childNodes[0].nodeValue);
document.write('" alt"');
document.write(x[i].getElementsByTagName('title')[0].childNodes[0].nodeValue);
document.write('"/></a>');
}
</script>

如果它有任何帮助,这是一个 xml 示例,您会看到照片有一个属性,它赋予它一个唯一的 ID。

<gallery>

<photo id="p0001">
<title>Pergola</title>
<path>photos/Pergola.jpg</path>
<thumb>photos/thumbs/Pergola.jpg</thumb>
<description>Please write something here!</description>
<date>
<day>04</day>
<month>04</month>
<year>2006</year>
</date>
</photo>

</gallery>

我愿意使用 php 作为 javascript 的替代品。

最佳答案

你可以添加

x = Array.prototype.slice.call(x).sort( function () {
return Math.random() > 0.5 ? 1 : -1
} );

紧接着

var x = xmlDoc.getElementsByTagName("photo");

这将创建一个随机排序的元素数组,前四个元素将由 for 循环迭代。

编辑

请注意,此方法不会对数组进行适当的随机洗牌,请参阅 Is it correct to use JavaScript Array.sort() method for shuffling? ,我不推荐它。

关于php - 使用 javascript 从 xml 文件加载一系列随机图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14667627/

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