【问题标题】:How can I check if an image exists with jquery? [duplicate]如何使用 jquery 检查图像是否存在? [复制]
【发布时间】:2013-08-16 05:30:18
【问题描述】:

我相信您已经多次看到这个问题,但我向您保证这是不同的。 我想知道如何使用带有 url 变量的图像路径来检查图像是否存在。 我想要这样的东西:

if ($('url').length ) {
    $(".mainContent").html("File exists");
} 
else
    $(".mainContent").html("File does not exists");`

希望你能尽快帮助我...

【问题讨论】:

  • 检查元素是否存在于 DOM 中,或者图像是否真的存在于服务器上?

标签: jquery image exists


【解决方案1】:

对于可能存在的图像,我发现最优雅的解决方案是使用 $ajax,例如:

$.ajax({
    url: 'your_image.jpg',
    type: "POST",
    dataType: "image",
    success: function() {
        /* function if image exists (setting it in div or smthg.)*/
    },
    error: function(){
       /* function if image doesn't exist like hideing div or setting default image*/


      } 

})

但是提醒一下,有些人坚持使用 GET 而不是 POST,但是 我没有任何问题,它就像一个魅力

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 2016-07-18
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2013-01-17
    • 2011-01-23
    相关资源
    最近更新 更多