Js:变量在点击时被覆盖

时间:2012-08-23 23:09:29

标签: javascript jquery

我被这个难倒,也许你可以帮助我。

这是我的HTML:

<ul class="wpsc_product_list_categories wpsc_product_list_categories_js">
<li><a href="#" id="products_all">All products</a></li>
<li><a href="#" class="wpsc_category_link "><span class="product_category_15">cat 1</span></a>
</li>
<li><a href="#" class="wpsc_category_link "><span class="product_category_12">cat 2</span></a></li>
</ul>

这是我的js:

jQuery(".wpsc_product_list_categories_js a").click( function() {    
    jQuery('.wpsc_product_list_categories a').removeClass('wpsc-current-cat');  
    jQuery(this).addClass('wpsc-current-cat');

    var className = jQuery(this).children().attr('class');

    jQuery('.products_list_product').fadeOut(300, function() { 
        jQuery('.products_list_product').removeClass('product_item_last');
        i = 2
        jQuery('.' + className).each(function(j){
            i = i + 1;
            if (i == 3) {
                jQuery(this).addClass('product_item_last'); 
                i = 0;
            }
        });
    });
    alert(className);
    jQuery('.' + className).fadeIn(300);
    return false;
});

这个想法是当你点击其中一个链接时,跨度的类存储在变量&#39; className&#39;中。当你点击它一次,它工作正常。当您再次单击它时,该变量突然变为&#39; the_original_class_name&#39;和&#39; product_item_last&#39;。这不应该发生,但我无法弄清楚原因。

有人有任何想法吗?

1 个答案:

答案 0 :(得分:2)

您在函数中使用this,但是您尝试在另一个范围内引用this

jQuery(".wpsc_product_list_categories_js a").click( function() {    
    jQuery('.wpsc_product_list_categories a').removeClass('wpsc-current-cat');  
    jQuery(this).addClass('wpsc-current-cat');

    var className = jQuery(this).children().attr('class');

    jQuery('.products_list_product').fadeOut(300, function() { 
        jQuery('.products_list_product').removeClass('product_item_last');
        var $this = $(this);      //this is the "this" that you want(i think)!!!!
        i = 2
        jQuery('.' + className).each(function(j){
            i = i + 1;
            if (i == 3) {
                $this.addClass('product_item_last');  //and use it here!!!!!
                i = 0;
            }
        });
    });
    alert(className);
    jQuery('.' + className).fadeIn(300);
    return false;
});​

enter image description here