我正在尝试为网站编写一个简单的图片库元素,但由于愚蠢的原因,我遇到了代码问题。我从来没有使用JavaScript,总是觉得很头疼。我已经尝试了各种其他图像画廊,但不能为我的生活让他们真正正常工作
我目前的HTML代码是这样的:
<!DOCTYPE html>
<html>
<head>
<title> Test of slider </title>
<script type="text/javascript" src="slider.js"></script>
</head>
<body>
<div class="slider" id="main">
<img src="#" class="mainImage" />
<div class="sliderImages" style="display: none;">
<img src="companion.jpg"/>
<img src="cookie.jpg" />
<img src="orange.jpg" />
<img src="orangeWhole.jpg" />
</div>
<div class="sliderButtons">
<a href="#" onclick="Slider.Slide('main', -1)"> Previous </a>
<a href="#" onclick="Slider.Slide('main', 1)"> Next </a>
</div>
</div>
</body>
</html>
使用这样的javascript:
this.Slider = new function(){
// Stores the indices for each slider on the page, referenced by their ID's
var indices = {};
var limits = {};
var images = {};
// Call this function after a major DOM change/change of page
this.SetUp = function(){
// obtain the sliders on the page
// TODO restrict to those within body
var sliders = document.getElementsByClassName('slider');
// assign the indices for each slider to 0
for(var i = 0; i < sliders.length; i++){
indices[sliders[i].id] = 0;
var sliderImages = document.getElementsByClassName('sliderImages');
var imagesTemp = sliderImages[0].getElementsByTagName('img');
images[sliders[i].id] = imagesTemp;
limits[sliders[i].id] = imagesTemp.length;
}
}
// advances a certain slider by the given amount (usually 1 or -1)
this.Slide = function(id, additive){
if(indices && id){
indices[id] = indices[id] + additive;
// Check limits
if(indices[id] < 0){
indices[id] = limits[id] - 1;
}
if(indices[id] >= limits[id]){
indices[id] = 0;
}
// alter img to be the new index
document.getElementById(id).getElementsByClassName('mainImage')[0].src = images[id][indices[id]].src;
}
}
}
答案 0 :(得分:1)
for(var slider in sliders)
{
// here slider is the index of the array. to get the object use sliders[slider]
}
然后你可以使用'getElementsByClassName'函数
修改
你已经在html的顶部包含了slider.js。首先,它加载js并尝试访问尚未创建的元素。将标记移动到页面底部。
sliderImages是一个包含classname sliderImages的div数组。只有一个满足。
var sliderImages // is a array with 1 item.
// to get the images use sliderImages[0].getElementsByTagName('img');
更改
this.Slide = new function(id, additive){
到
this.Slide = function(id, additive){ // otherwise it will be called when the page is loaded with undefined values.
使用引号
点击链接调用Slider.Slide('main', 1)
答案 1 :(得分:0)
您使用的是我不知道的方法(或者您忘记了“s”)
var sliderImages = slider.getElementByClassName('sliderImages');
我会使用类似下面的代码。重要的是,sliderImages将是“silderImages”类的任何数组
var sliderImages =slider.getElementsByClassName("sliderImages")