jQuery这个查找选择器无法正常工作

时间:2017-02-03 15:48:42

标签: javascript jquery

有没有人知道我在这里做错了什么?在console.log上它返回750或2000但在我的条件下似乎没有找到图标并添加图标类。

JS

$("a.image-select").click(function(){

    $('.loading').show();
    selectedImage = $(this).data('image');
    $("a.image-select").removeClass('selected');
    $(this).addClass('selected');
    $('.image-warning').hide();
    $(".image-original").attr('src', "imgd.php?src="+selectedImage+"&quality=100&w=500&h=500&cf");
    $(".image-optimised").attr('src', "imgd.php?src="+selectedImage+"&quality=100&w=500&h=500&cf");

    $.ajax({
        url: "imgd.php?src="+selectedImage+"&quality=100&json",
        dataType: "json"
    }).success(function(data){
        $('.image-details-quality').html('100');
        var sizeInMB = (JSON.stringify(data['size']) / (1024*1024)).toFixed(2);
        var sizeInKB = (JSON.stringify(data['size']) / 1024).toFixed(2);
        $('.image-details-size').html(sizeInMB + 'mb' + ' / ' + sizeInKB + 'kb');
        $('.image-details-dims').html(data['width'] + 'px' + ' x ' + data['height'] + 'px');
        $('.image-details-type').html(data['mimeType']);
        // if image is more than 2000 show error
        if(data['width'] > 2000){
            $('.image-warning').show();
        }
        // set thumbnail icons
        if(data['width'] == 2000){
            $(this).find('span.device-icon').addClass('glyphicon-phone');
        } else if(data['width'] == 750) {
            $(this).find('span.device-icon').addClass('glyphicon-blackboard');
        }
        console.log(data['width']);
        $('#slider').slider('refresh');
        $('.image-details').show();
        $('.loading').hide();
    });

});

此部分有问题

// set thumbnail icons
if(data['width'] == 2000){
    $(this).find('span.device-icon').addClass('glyphicon-phone');
} else if(data['width'] == 750) {
    $(this).find('span.device-icon').addClass('glyphicon-blackboard');
}

HTML示例

<a href="#" data-image="LUXE-ESSENTIALS-MOB.jpg" class="image-select selected">
    <span class="select-icon glyphicon glyphicon-ok-circle"></span>
        <img src="imgd.php?src=LUXE-ESSENTIALS-MOB.jpg&amp;quality=100&amp;width=80&amp;height=80&amp;crop-to-fit" data-pin-nopin="true">
    <span class="device-icon glyphicon"></span>
</a>

1 个答案:

答案 0 :(得分:7)

成功回调中的$(this)不再引用被点击的元素,因此您应该将其保存在变量中,然后在回调中使用它,如:

var _this = $(this);

$.ajax({
    url: "imgd.php?src="+selectedImage+"&quality=100&json",
    dataType: "json"
}).success(function(data){
    ...
    // set thumbnail icons
    if(data['width'] == 2000){
        _this.find('span.device-icon').addClass('glyphicon-phone');
    } else if(data['width'] == 750) {
        _this.find('span.device-icon').addClass('glyphicon-blackboard');
    }
    ...
});

或者您也可以使用上下文属性,如:

$.ajax({
    context: this,
    url: "imgd.php?src="+selectedImage+"&quality=100&json",
    dataType: "json"
    success: function(response){
        //You can use $(this) now
    }
});

希望这有帮助。