编程语言
首页 > 编程语言> > 带有标题问题的Javascript幻灯片

带有标题问题的Javascript幻灯片

作者:互联网

所以我在使用javascript对幻灯片进行字幕设置时遇到问题,有人可以告诉我哪里出错了.我的代码如下:

JavaScript文档

var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");

function moveToNextSlide()
{
if (index >= 5){index = 0}
var img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();

}


function CaptionSlide()
{

if( img.attr("src") == "movieImages/img1.jpg")
    document.getElementById("captionbar").innerHTML="Up!";
else if(img.attr("src") == "movieImages/img2.jpg")
    document.getElementById("captionbar").innerHTML="Monsters Inc";
else if(img.attr("src") == "movieImages/img3.jpg")
    document.getElementById("captionbar").innerHTML="Madagascar";
else if(img.attr("src") == "movieImages/img4.jpg")
    document.getElementById("captionbar").innerHTML="Finding Nemo";
else if(img.attr("src") == "movieImages/img5.jpg")
    document.getElementById("captionbar").innerHTML="Ice Age";
}

HTML文档

<div class="slides">
    <img id="img1" src="">
</div>
<input type="image" src="images/Next.png" id="button" onClick="javascript:moveToNextSlide()" title="Next" >
<div id ="captionbar"></div>

还要注意,我在“inspect element”中得到了这个错误:
未捕获的TypeError:无法调用null的方法’attr’

修订

var index = 0;
var titles=[1,2,3,4,5];
var img = document.getElementById("img1");

function moveToNextSlide()
{
if (index >= 5){index = 0}
img = document.getElementById("img1");
var slideName = "movieImages/img" + titles[index++] + ".jpg";
img.src=slideName;
CaptionSlide();

}

function CaptionSlide()
{
    window.onload = function(){
    if( img.src === "movieImages/img1.jpg")
    document.getElementById("captionbar").innerHTML="Up!";
    else if(img.src === "movieImages/img2.jpg")
        document.getElementById("captionbar").innerHTML="Monsters Inc";
    else if(img.src === "movieImages/img3.jpg")
        document.getElementById("captionbar").innerHTML="Madagascar";
    else if(img.src === "movieImages/img4.jpg")
        document.getElementById("captionbar").innerHTML="Finding Nemo";
    else if(img.src === "movieImages/img5.jpg")
        document.getElementById("captionbar").innerHTML="Ice Age";
    }
}

HTML保持与以前相同.
没有错误引用,但函数不会写任何文本.

解决方法:

用img.src ==“你的图像名称”替换所有img.attr(‘src’).

例如:

img.src=="movieImages/img1.jpg"

当您使用纯JavaScript时,您不能使用attr()这是JQuery的方法.

标签:javascript,slideshow,html
来源: https://codeday.me/bug/20190703/1366694.html