第二次单击后功能有效

时间:2013-12-23 13:18:22

标签: jquery

这是我的代码的一部分,我不明白为什么它在第二次点击后有效。它应该在第一次点击后工作 JSFIDDLE

jQuery(document).ready(function($){
    var mainfunction = function(){
        var $eachblocks = $(".top10_month .periods");
        var $blockhead = $(".block-head__link");
        $blockhead.on("click", function(e){

            var $this = $(this);
            var typelink = $(".block-head__link.active").attr("data-date");
            e.preventDefault();
            $this.parents("ul").find("a").removeClass("active");
            this.className += " active";
            $this.parents(".block-parent").find(".periods").removeClass('active');
            $this.parents(".block-parent").find(".periods[data-period="+typelink+"]").addClass('active');
        });
    };
    mainfunction();
});

4 个答案:

答案 0 :(得分:4)

您需要从点击的元素中读取数据

var typelink = $this.data("date");

演示:Fiddle

第一次单击时,您正在读取活动元素的数据,该活动元素是在活动类被分配给当前单击的元素之前的12月

答案 1 :(得分:1)

你应该使用$this中的当前对象,它总是在DOM中查找第一个$('.block-head__link.active'),你点击事件将不会第一次工作:

var typelink = $this.attr("date"); // $this change here

Demo

答案 2 :(得分:1)

试试这个

工作小提琴:jsfiddle.net/kngU8/5

$blockhead.on("click", function(e){
        var $this = $(this);
        var typelink = $this.attr("data-date"); 
        $this.parents("ul").find("a").removeClass("active");
        this.className += " active";
        $this.parents(".block-parent").find(".periods").removeClass('active');
        $this.parents(".block-parent").find(".periods[data-period="+typelink+"]").addClass('active'); 
        return false;
    });

答案 3 :(得分:0)

工作jsfiddle:http://jsfiddle.net/patelmilanb1/kngU8/6/

$(document).ready(function () {
    var myfunction = function () {
        $(".block-head__link").on("click", function (e) {
            e.preventDefault();
            var typelink = $(this).data("date");
            $('.block-head__menu').removeClass("active");
            $(this).addClass("active");
            $(".periods").removeClass('active');
            $(".periods[data-period=" + typelink + "]").addClass('active');
        });
    };
    myfunction();
});
相关问题