首页 > 解决方案 > 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>

看看它在哪里显示“开始图像标题”我希望代码显示在这里。我知道这是一个菜鸟问题,但我很少编码。我只是希望它注入到该部分中,以便我可以设置它的样式。

DOM 的图片

如果有帮助,该工具也已上线。https://tools.akanoodles.com/

标签: javascriptdocument

解决方案


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);

推荐阅读