【问题标题】:Append an image to HTML with jQuery, but then replace appended image with new image使用 jQuery 将图像附加到 HTML,然后用新图像替换附加的图像
【发布时间】:2020-06-11 22:36:52
【问题描述】:

我正在尝试在单击小图片库时在其上方显示较大版本的图片。

目前它一直在附加图像而不删除旧的附加图像。

有人知道我会怎么做吗?

<script>
jQuery(document).ready(function() {
    //on click of image
    jQuery("#node-facility-full-group-gallery img").click(function(event) {
        event.preventDefault();
        //get image src
        var imgToDisplay = jQuery(event.target).attr("src");
        //append image to page
        $('<img src="' + imgToDisplay + '">').load(function() {
            $(this).appendTo('#node-facility-full-group-gallery h2');
        });
    })
});
</script>

【问题讨论】:

  • append 表示添加,如果要清除元素先使用.empty()

标签: html jquery image replace


【解决方案1】:

您可以使用“.remove()”删除之前添加的图像,为此您需要在添加图像时为其提供一个 ID。

例子:

jQuery(document).ready(function() {
  //on click of image
  jQuery("#node-facility-full-group-gallery img").click(function(event) {
    event.preventDefault();
    // remove prevously appended image
    jQuery('#node-facility-full-group-gallery h2').find('#appendedImg').remove();
    //get image src
    var imgToDisplay = jQuery(event.target).attr("src");
    //append image to page
    $('<img id="appendedImg" src="' + imgToDisplay + '">').load(function() {
      $(this).appendTo('#node-facility-full-group-gallery h2');
    });
  })
});

【讨论】:

    猜你喜欢
    • 2021-01-26
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2017-11-30
    • 2014-06-15
    • 1970-01-01
    • 2012-06-07
    • 2011-06-05
    相关资源
    最近更新 更多