在JavaScript中用select using数组替换多个img



-大家好!-

在几个月的时间里尝试了多种方法后,我来到这里询问是否有人能解决我的问题:我想有一个连续显示多个图像的页面,当我在select栏中更改所选索引时,更改所有这些图像,我不想添加图像,而是通过我在javascript中放入数组中的其他图像来更改图像(我使用数组中的链接,这些链接将进入img的src(,这是我的代码,可以更多地了解我想要什么和我尝试了什么:

注意:

-我知道用JavaScript操作img是不好的,但我不想在html中使用iframe,因为每当数组中的图像少于最大可能的iframe标签(此处为300(时,它就会显示一些空页面,而且加载起来很麻烦。(我还发现img标签非常适合我的需求(。

-如果我的代码很乱或不好,很抱歉,谢谢你帮助我!

HTML

<div class="col-6">
<select class="episodes listes form-select form-select mb-3" onchange="listeChap()">
<option selected>Choose a Chapter</option>
<option value="0">Chapter 1</option>   
<option value="1">Chapter 2</option>
<option value="2">Chapter 3</option>
<option value="3">Chapter 4</option>
<option value="4">Chapter 5</option>
...
</select> 
</div>
<div class="col-12 text-center">
<img id="frame1" class="img-fluid"></img>
<img id="frame2" class="img-fluid"></img>
<img id="frame3" class="img-fluid"></img>
<img id="frame4" class="img-fluid"></img>
<img id="frame5" class="img-fluid"></img>
...
<img id="frame300" class="img-fluid"></img>
</div>

JavaScript

//here each "epsX" array is the X selected chapter, and in each chapter we have the img urls that I want to show
var eps1 = [
'some_url_img.jpg',
'some_url_img.jpg',
'some_url_img.jpg',
];
var eps2 = [
'some_url_img.jpg',
'some_url_img.jpg',
'some_url_img.jpg',
];
var eps3 = [
'some_url_img.jpg',
'some_url_img.jpg',
'some_url_img.jpg',
];
.
.
.
function listeChap() {

var elt = document.querySelector('select, .episodes');
//the name of each arrays that we will add an X after to know which chapter it is
var k = 'eps';
var link, count, frameX;
//300 is the total img tag number in HTML, didn't find how to put a var for it but it's ok like this I think
for(count = 0; count < 300; count++){
//having proper frame number for the getElementById
frameX = 'frame' + count+1;
//create a var that uses the array's name with a dyanmic number to have the links of the proper chapter => "epsX[]"
link = eval(k + elt.selectedIndex + '[' + count + ']' + ';');
//gives to the frameX id of img the proper link
document.getElementById(frameX).src = link;
}
}

您的问题在这里:

frameX = 'frame' + count+1; // results frame01

应该是:

frameX = 'frame' + (+count + 1); // results frame1
// +count treats count as a number not a string

您的简化小提琴:https://jsfiddle.net/2174q8nL/2/

最新更新