如何使用轮播中的图像URL显示图像?

时间:2017-06-18 05:56:51

标签: javascript jquery json twitter-bootstrap

我无法通过图片网址(JSON数据)在轮播中显示图片。我试图在jquery中使用attr()设置属性,但无法实现所需的结果。这是我的代码:

<div class="col-md-8">
            <div id="myCarousel" class="carousel slide" data-ride="carousel">
                <!-- Indicators -->
                <ol class="carousel-indicators">
                    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                    <li data-target="#myCarousel" data-slide-to="1"></li>
                    <li data-target="#myCarousel" data-slide-to="1"></li>
                </ol>

                <!-- Wrapper for slides-->
                <div class="carousel-inner">
                    <div class="item active">
                        <img src="" alt="myimage1" style="width: 100%">
                        <div class="carousel-caption">
                            <h3>Your news title</h3>
                            <p>news in short</p>
                        </div>
                    </div>
                    <div class="item">
                        <img src="" alt="myimage2" style="width: 100%">
                        <div class="carousel-caption">
                            <h3>Your news title</h3>
                            <p>news in short</p>
                        </div>
                    </div>
                    <div class="item">
                        <img src="" alt="myimage3" style="width: 100%">
                        <div class="carousel-caption">
                            <h3>Your news title</h3>
                            <p>news in short</p>
                        </div>
                    </div>
                </div>

                <!-- Left and Right controls -->
                <a class="left carousel-control" href="#myCarousel" data-slide="prev">
                    <span class="glyphicon glyphicon-chevron-left"></span>
                    <span class="sr-only">Previous</span>
                </a>
                <a class="right carousel-control" href="#myCarousel" data-slide="next">
                    <span class="glyphicon glyphicon-chevron-right"></span>
                    <span class="sr-only">Next</span>
                </a>
            </div>
        </div> 

在.js文件中:

$(document).ready(function() {

$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=my-api-key',function(json) {
        console.log(json);
        console.log(json.articles.length);

        for(var i = 0 ;i<3;i++){  //As my carousel contains only 3 images
            $(".item").attr("src",json.articles[i].urlToImage);
        }

    });
});

API的JSON响应: enter image description here

1 个答案:

答案 0 :(得分:2)

$(".item").attr("src",json.articles[i].urlToImage);

应该是

$(".item img").attr("src",json.articles[i].urlToImage);