1

我有一个真正简单的 jQuery 显示函数,当单击链接时,它会将图像加载到 DIV 中。

$(function(){
jQuery(".gallery-item a").click(function(evt) {
    evt.preventDefault();
    jQuery("#imageBox").empty().append(
        jQuery("<img>", { src: this.href})
    );
});
});

有没有办法添加默认图像,以便在加载页面时已经在 div 中有一个图像?

4

2 回答 2

1
$(function () {
    $(".gallery-item a").click(function (evt) {
        evt.preventDefault();
        var box = $("#imageBox").html('<img src="default.jpg" />');

        $("<img>", {src: this.href}).load(function () {
            box.empty().append(this);
        });
    });
});
于 2012-09-03T13:16:42.463 回答
0

尝试这个:

$(function() {
    jQuery(".gallery-item a").click(function(evt) {
        jQuery("#imageBox").empty().append(
           jQuery("<img />", { src: $(this).attr("href") })
        );
        return false;
    });
});​

编辑评论:

假设图片的url在属性“data-urlimage”标签“a”中

html:

<div class="gallery-item">
 <a data-urlimage="/img/myimage.jpg" href="#">click here</a>
</div>

Javascript:

$(function() {
    jQuery(".gallery-item a").click(function(evt) {

         var img = new Image();
         img.src = $(this).data("urlimage");
         img.onload = function(){
             jQuery("#imageBox").empty().append(img);
         };

        return false;
    });
});​

查看图像事件

编辑:查看如何创建更好的对象“图像”

于 2012-09-03T13:19:34.947 回答