簡體   English   中英

如何在更新后刷新特定圖像?

[英]How can I refresh a specific image after an update?

我有幾個帶有唯一ID的div標簽,在針對特定圖像的點擊事件后,我正在嘗試刷新它。 我怎樣才能做到這一點? 這是我到目前為止的代碼:

HTML:

<div class="photo_gallery_container" <?php echo($div_id); ?>>
    <table class="table table-bordered table-condensed">
        <thead >
            <tr style="background-color: #f5f5f5;">
                <th colspan="2" style="text-align: right;"><span style="cursor:pointer" id="delimg_<?php echo($id); ?>" class="delimg"><span class="label label-important">Delete</span></span></th>
            </tr>               
        </thead>
        <tbody>
            <tr>
                <td>
                    <img src="<?php echo($url['url'])?>" style="height:120px;"/>
                </td>
                <td>
                    <a href="#" id="rotateimg_<?php echo($id); ?>" class="rotateimg">Rotate</a>
                </td>
            </tr>
        </tbody>
    </table>
</div>

我的旋轉點擊事件如下所示:

$('.rotateimg').click(function(e) {
    e.preventDefault();
    var id = $(this).attr('id').substr(10);

    $.post("/functions/photo_functions.php", { f: 'rotate', imgid: id }, function(status){

        if (status == 'true') {

            // How can I reload the specific image after being rotated

        }
    });

});            

只需將查詢字符串附加到img的URL(例如?v=1 ),這會欺騙瀏覽器認為它是一個新圖像。

這是一個例子(假設id是頁面上圖像的id):

$('#' + id).prop('src', function(i, v)
{
    var separator = v.indexOf('?') == -1 ? '?' : '&';

    return v + separator + 'v=' + ( new Date() ).getTime();
});

由於看起來你的頁面上的img沒有ID,你可以遍歷DOM來找到它,就像這樣:

$(this).parent().prev().find('> img')

插件怎么樣?

$.fn.refresh(function() {
  return this.each(function() {
    var $this = $(this);
    var source = $this.data('orig-src');
    var timestamp = (new Date()).getTime();

    if (!source) {
      $this.data('orig-src', $this.prop('src'));
      source = $this.data('orig-src');
    }

    if (source.indexOf('?') != -1) {
      $this.prop('src', source + '&t=' + timestamp)
    } else {
      $this.prop('src', source + '?t=' + timestamp)
    }
  });
});

現在你可以在<img />標簽上調用它:

$('img.foo').refresh();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM