jquery - 在 1 个 div 标签中加载 1 个随机图像(可能是 10 个图像)
问题描述
我不是一个真正的程序员,需要一些帮助。我需要一个插入 div 标签的脚本,并且当页面从外部 js 文件加载时,在该 div 标签内有一个随机图像加载(来自 10 个列表)。
我搜索和搜索并尝试了不同的方法,但确实需要帮助。
谢谢
解决方案
下面的解决方案使用了 jQuery,但是没有它也可以通过简单的方式实现
$(document).ready(function() {
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var imageUrls = [
"https://www.gstatic.com/webp/gallery3/1.sm.png",
"https://www.gstatic.com/webp/gallery3/2.sm.png",
"https://www.gstatic.com/webp/gallery3/3.sm.png"
];
var randomImage = imageUrls[randomInt(0, imageUrls.length - 1)];
$(".container").append("<img alt='" + randomImage + "' src='" + randomImage + "'</>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
</div>
更新 - 完整的 HTML 有效页面内的相同答案
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script type="text/javascript">
/**
* Loads a random number
*/
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// List of urls
var imageUrls = [
"https://www.gstatic.com/webp/gallery3/1.sm.png",
"https://www.gstatic.com/webp/gallery3/2.sm.png",
"https://www.gstatic.com/webp/gallery3/3.sm.png"
];
function loadRandomImage() {
var randomImage = imageUrls[randomInt(0, imageUrls.length - 1)];
$(".container").append(
"<img alt='" + randomImage + "' src='" + randomImage + "'</>");
}
// This function executes when the DOM is ready,
// e.g., when the entire page is loaded
$(document).ready(function() {
loadRandomImage()
});
</script>
</head>
<body>
<div class="container">
</div>
</body>
</html>
推荐阅读
- android - InCallService 和 ConnectionService 的区别
- algorithm - 到达终点的最短距离
- python - 如何在熊猫中汇总总和并将唯一行值转换为列名?
- python - 使用从表单保存的值来呈现页面
- javascript - 如何使用 JS / Angular 以编程方式在服务器中更新和保存嵌入式交互式表单 pdf?
- javascript - React组件的componentDidMount中的耗时函数调用
- algorithm - 这个函数的正确时间复杂度是多少
- javascript - 在 DropDown 选择中绘制出独特的结果
- youtube - Youtube Data API - 如何获取我的私人和未列出的视频
- javascript - 与 Vue 中的父级同步道具?