未捕获的TypeError:无法读取未定义的属性'src'

时间:2013-09-05 09:45:18

标签: javascript jquery

我正在尝试实现幻灯片放映,我已经编写了以下代码,但由于这一行$('#contain').children();正在返回[object Object]而不是我在其上的DOM元素,因此它无法正常工作可以迭代?

Complete code:

function startSlideShow(interval) {
//var slides = $('#contain').children();
var slides = $('#contain').children().get();
console.log("0: " + slides);
slides.each(function () {
    console.log($(this));
});
for (var i = 0; i < slides.length; i++) {
    setTimeout(
        function () {
            var slide = $(slides[i]).children();
            console.log("1: " + slide);
            $('#currentImage').attr('src', slide[0].src).fadeIn(interval * 100);
            $('#slideDesc').html(slide[1].innerHTML).fadeIn(interval * 100);
        }, interval * 1000);
}
}

in the html:

<article id="imageShow">
    <div class="image">
        <img src="" id="currentImage" />
    </div>
    <div id="imageCover"></div>
</article>

<article id="contain">
    <div class="image">
        <img src="http://i.imgur.com/925p6M5.jpg" />
        <span>1Lorem Ipsum is simply dummy text of the printing and typesetting industry. </span>
    </div>
    <div class="image">
        <img src="http://i.imgur.com/dbBu5rk.jpg" />
        <span>2 Lorem Ipsum is simply dummy text of the printing and typesetting industry. </span>
    </div>
    <div class="image">
        <img src="http://i.imgur.com/VFxPGEi.gif" />
        <span>3 Lorem Ipsum is simply dummy text of the printing and typesetting industry. </span>
    </div>
</article>

并且在控制台中我得到如下错误:'未捕获的TypeError:无法读取未定义的属性'src'

4 个答案:

答案 0 :(得分:2)

缺少' ..我认为这是一个错字......这里有一个问题,

  $('#currentImage').attr('src', slide[0].src).fadeIn(interval * 100);

您没有id为currentImage的元素,因此您收到错误消息,指出src属性未定义。

<强>更新

试试这个

function startSlideShow(interval) {
var slides = $('#contain').children();
slides.each(function (index, value) {
    setTimeout(function () {
        var slide = $(value);
        $('#currentImage').attr('src', slide.find('img').attr('src')).fadeIn(interval * 100);
        $('#slideDesc').html(slide.find('span').html()).fadeIn(interval * 100);
    }, interval * 1000);
});
}

答案 1 :(得分:1)

您正在寻找的可能是

function startSlideShow(interval) {
    var slides = $('#contain').children();
    slides.each(function (i, v) {
        setTimeout(function () {
            var slide = $(v);
            $('#currentImage').attr('src', slide.children('img').attr('src')).fadeIn(interval * 100);
            $('#slideDesc').html(slide.children('span').html()).fadeIn(interval * 100);
        }, i * interval);
    });
}

演示:Fiddle

答案 2 :(得分:0)

<强>替换

var slides = $('#contain).children().get();

。通过

var slides = $('#contain').children().get();

您忘记了'选择器中的id

如果要选择子元素,则需要指定要获取的子元素。

var slides = $('#contain').children('div').get();

答案 3 :(得分:0)

尝试指定子元素,而不是简单地提及children()。