html - 尝试插入图像时从 jQuery 中出现的对象 HTMLImageElement
问题描述
所以这就是我想要做的:显示一个用图像随机创建的模式,但不断出现 [object HTML Image Element] 框
var s1 = [];
s1[0] = new Image();
s1[0].src = '11.jpg';
s1[1] = new Image();
s1[1].src = '12.jpg';
s1[2] = new Image();
s1[2].src = '13.jpg';
s1[3] = new Image();
s1[3].src = '14.png';
s1[4] = new Image();
s1[4].src = '15.png';
var s2 = [];
s2[0] = new Image();
s2[0].src = '21.jpg';
s2[1] = new Image();
s2[1].src = '22.jpg';
s2[2] = new Image();
s2[2].src = '23.jpg';
s2[3] = new Image();
s2[3].src = '24.png';
s2[4] = new Image();
s2[4].src = '25.jpg';
var s3 = [];
s3[0] = new Image();
s3[0].src = '31.jpg';
s3[1] = new Image();
s3[1].src = '32.jpg';
s3[2] = new Image();
s3[2].src = '33.jepg';
s3[3] = new Image();
s3[3].src = '34.jpg';
s3[4] = new Image();
s3[4].src = '35.gif';
现在创建了数组,我希望它随机选择 5 个中的 1 个来使用,这似乎工作正常
p1 = Math.floor(Math.random() * 5 + 1);
p2 = Math.floor(Math.random() * 5 + 1);
p3 = Math.floor(Math.random() * 5 + 1);
if(p1 == 1) {
p1 = s1[0];
} else if (p1 == 2) {
p1 = s1[1];
} else if (p1 == 3) {
p1 = s1[2];
} else if (p1 == 4) {
p1 = s1[3];
} else if (p1 == 5) {
p1 = s1[4];
}
如果为 p2 和 p3 完成了完全相同的 if/else if 结构,我不会复制并粘贴它以节省空间,现在我想输出最终模式,也就是当我得到对象 HTML 图像元素出现时
while(repeat > 0){
pattern = p1 + p2 + p3 + pattern;
repeat --;
}
correctAnswer = 1;
$("#patternSpan").html(pattern)
解决方案
问题
相互添加图像是什么意思?是否应该将每个像素的所有 rgb 值加在一起?它应该创建一个附加像素的新图像吗?附在哪一边?
对于语言自动执行这些事情都没有意义,所以这里发生了什么:
pattern = p1 + p2 + p3 + pattern;
是 javascript 正在尝试确定+
是数字加法还是字符串连接。
因为值不是数字,所以 JS 默认为字符串连接。
当您尝试字符串连接时,非字符串会发生什么?
JS 先调用.toString()
值
原来图像的字符串值是[object HTML Image Element]
解决方案
所以你想要做的是将图像附加到#patternSpan
. 因此,不要将图像添加在一起,而是将它们附加到跨度:
$("#patternSpan").append(p1, p2, p3)
边注
您可以通过执行以下操作来清理您随机选择图像的部分:
idx1 = Math.floor(Math.random() * 5 + 1);
idx2 = Math.floor(Math.random() * 5 + 1);
idx3 = Math.floor(Math.random() * 5 + 1);
p1 = s1[idx1];
p2 = s2[idx2];
p3 = s3[idx3];
您还应该避免重复使用变量,例如p1
用于不同类型的事物,即存储随机数和存储图像。
如果一个变量可以包含多种可能的类型,您更有可能遇到与类型相关的错误。
推荐阅读
- firebase - 用于实时搜索/提前输入的 Firebase 数据建模
- javascript - 如何区分用于 DOM 函数的相同 div?
- spring - 从 Spring-dependency-management 插件中提取依赖版本
- javascript - Next.js 中的 Trustpilot 信任框
- symfony - Symfony 4 通过数据库获得 cas 和角色的身份验证
- python - Python Tkinter-每次单击时清除文本框并使用数字组分隔符显示
- python - 在丢失整个数据集后构建训练模型
- android - 在 HTML 页面中使用 drawable
- android - Firebase 推送通知?
- visual-studio - 检查器失败:端口已用于 Javascript webdriverio 自动化项目