【问题标题】:href depending on ajax success or failhref 取决于 ajax 成功或失败
【发布时间】:2011-09-30 03:59:51
【问题描述】:

在我的 Wordpress 中,我将自定义附件尺寸设置为 128x79 和 896x277。我的图片肯定会大于 128x79。如果图像小于 896x277,它会裁剪掉大于最大尺寸的图像,并将另一个设置为最大尺寸。这意味着 500x300 的图像将被裁剪为 500x277。

假设在我的页面上我有一个带有 href http://domain.com/files-128x79.jpg 的图像,如果它存在,我想用 files-896x277.jpg 替换 files-128x79.jpg,否则,以高度为优先,找到最大的图像。

好的...我决定简化我的问题以使其更容易。我现在要做的就是检查 files-896x277.jpg 是否存在,如果不存在,我希望它输出 files.jpg。到目前为止我已经有了这个,但似乎无法设置锚href。

$rewrite.find('a').each(function(index, element) {
    $.ajax({
        url : $(this).children().attr('src').replace('-128x79.', '-896x277.'),
        type: 'head',
        success : function() {
                $(this).attr('href', $(this).children().attr('src').replace('-128x79.', '-896x277.'));
        },
        error : function(xhr, d, e) {
            if (xhr.status == 404) {
                $(this).attr('href', $(this).children().attr('src').replace('-128x79.', '.'));
            }
        }
    });
});

我做错了什么?

【问题讨论】:

    标签: jquery file-exists


    【解决方案1】:

    在 AJAX 回调中,this 中的内容是什么?它仍然是导致事件的因素吗?如果有,是哪个事件? AJAX 结果事件?

    我建议将this 保存到一个局部变量中,以确保它包含您所期望的:

    $(function () {
        var that = $(this);
        $.ajax({
        url : that.children()....
    

    【讨论】:

    • 好吧var $rewrite = $('.gallery-thumbs-list');和ajax在$rewrite.find('a').each()..所以$(this)应该是每个.gallery-thumbs-list a
    • 实际上.. 它正在工作.. 只是它破坏了我的画廊插件......太棒了。
    • 我想我明白了。我将ajaxComplete 链接到$rewrite.find('a').each() 并将图库代码作为函数放入其中。
    【解决方案2】:

    是的,你可以这样做:

    var image = 'files-128x79.jpg';
    $(function () {
        $.ajax({
            url : 'search_images.php',
            success : function(filelist) {
                //YOu have the filelist in a string. Just parse it to find the image
                ...
                var imageExists = (filelist.indexOf(image) >= 0); //Search the image
                if (!imageExists ) {
                    alert('The image was not found');
                }
            },
        });
    });
    

    PHP:

    search_images.php (linux)
    echo `ls /images/files-*.jpg`; //This will list all the images in your directory
    

    希望这会有所帮助。干杯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-30
      • 2015-08-27
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多