javascript - JS 注入的代码显示在错误的位置 - 我该如何解决?
问题描述
我使用我在网上找到的一些代码创建了一个随机卡片选择器。我遇到的问题是代码注入的位置。
我希望它在部分而不是在正文末尾显示代码。
JS 看起来像这样:
//find the length of the array of images
var arrayLength = imageArray.length;
var newArray = [];
for(var i = 0; i < arrayLength; i++) {
newArray[i] = new Image();
newArray[i].src = imageArray[i].src;
newArray[i].width = imageArray[i].width;
newArray[i].height = imageArray[i].height;
}
// create random image number
function getRandomNum(min, max) {
// generate and return a random number for the image to be displayed
imgNo = Math.floor(Math.random() * (max - min + 1)) + min;
return newArray[imgNo];
}
// 0 is first image and (preBuffer.length - 1) is last image of the array
var newImage = getRandomNum(0, newArray.length - 1);
// remove the previous images
var images = document.getElementsByTagName("img");
var l = images.length;
for(var p = 0; p < l; p++) {
images[0].parentNode.removeChild(images[0]);
}
// display the new random image
document.body.appendChild(newImage);
}
HTML 看起来像这样:
<body class="bg-extra-dark-gray small-section text-center">
<section>
<div class="container">
<div class="row">
<div class="col-12 tiny-screen page-title-medium text-center d-flex flex-column justify-content-center">
<!-- start page title -->
<h1 class="alt-font text-white font-weight-600 m-0 letter-spacing-1 margin-5px-bottom">
Brainstorm Card Generator
</h1>
<!-- end page title -->
<!-- start sub title -->
<div class="text-deep-pink margin-25px-bottom">
Press the button to display a new card
</div>
<!-- end sub title -->
<!-- start button title -->
<div>
<button class="btn btn-transparent-white btn-rounded btn-medium text-link-white inner-link margin-25px-bottom" onclick="displayRandomImages();">
Display Images
</button>
<!-- end button title -->
</div>
<!-- start image title -->
<div>
<img src="img/info/directions-00.png" />
</div>
</div>
</div>
</div>
</section>
看看它在哪里显示“开始图像标题”我希望代码显示在这里。我知道这是一个菜鸟问题,但我很少编码。我只是希望它注入到该部分中,以便我可以设置它的样式。
如果有帮助,该工具也已上线。https://tools.akanoodles.com/
解决方案
JavaScript 所做的最后一件事是将新图像附加到文档的正文中。那是在文件的末尾。
这条线
// display the new random image
document.body.appendChild(newImage);
您需要将其替换为
document.querySelector("CSS Selector, where on the page you like to append your image").appendChild(newImage);
推荐阅读
- php - 使用 ssp 类复杂函数给出未定义的偏移量:0 错误
- ruby-on-rails - 在 Rails 上使用 Semantic UI 创建汉堡导航栏
- python - 安装并激活具有不同python版本的virtualenv后,我得到了相同的python版本
- javascript - 是否有“YYYY-MM-DD”的格式预设
- postgresql - 在 Postgres 中执行访问路径选择的源代码在哪里?
- functional-programming - 为什么 Elixir 的 Enum.count 不返回数字?
- reactjs - 上下文 API 从任何地方消费
- java - 通过 Java 服务器页面/Java 单击时动态创建带有“按钮”的文件夹
- ios - 如何从 UITableView 单元格获取数据到全局变量
- python - JSON,列表可能为空 - 什么类型?