Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

jquery - Can I get the image and load via ajax into div

I have the code below and what I need to do is load the image from the href into a div via ajax... Any help appreciated. I believe that load() can't load images like this?

    <ul id="list">
    <li class="list-item-1"><a href="images/image1.jpg">Image 1</a></li>
    <li class="list-item-2"><a href="images/image2.jpg">Image 2</a></li>
    <li class="list-item-3"><a href="images/image3.jpg">Image 3</a></li>
    <li class="list-item-4"><a href="images/image4.jpg">Image 4</a></li>
    </ul>
<div id="image-holder"></div>

Many thanks, C

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to also remove the currently appended image. Here it is with a click event and Image instead of appending markup.

$('#list li a').click(function () {
    var url = $(this).attr('href'),
    image = new Image();
    image.src = url;
    image.onload = function () {
        $('#image-holder').empty().append(image);
    };
    image.onerror = function () {
        $('#image-holder').empty().html('That image is not available.');
    }

    $('#image-holder').empty().html('Loading...');

    return false;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...