Function work after second click

此生再无相见时 提交于 2019-12-03 00:42:00

问题


Anyboby help. Why function add class active this.parents(".block-parent").find(".periods[data-period="+typelink+"]").addClass('active') work after second click? need to be done after first click! link for not right example http://jsfiddle.net/kngU8/

Page.contentSort = 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');
    });
};

回答1:


because in first click you initialize the code so it works in second click! common logic use $(function()); like this

$(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');
});

});

try this this should work




回答2:


It's because you're using this

var typelink = $(".block-head__link.active").attr("data-date")

to find the link you've just clicked on, and you haven't dealt with changing the classes yet so it's getting the previous element you gave the class active to. The following will return the correct data-date value of the clicked element, not one you think it might be that's saught by class name.

var typelink = $(this).data("date");
// var typelink = $(this).attr("data-date"); // this isn't how data is used

http://jsfiddle.net/kngU8/7/



来源:https://stackoverflow.com/questions/20743851/function-work-after-second-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!