Jquery,循环除第一个之外的其他点击

时间:2014-02-27 15:59:05

标签: jquery css

所以我有一些代码,其目的是使用.load()加载类似于Facebook的框。

代码的工作原理是:Onclick检查是否隐藏。如果没有,则.load然后.toggle。再次Onclick,检查div是否可见,如果是,则隐藏.toggle

现在div被隐藏了,它将再次运行代码的第一部分。我想阻止这一点,并在第一次点击后运行else函数。

如何通过开关实现这一目标?

$(".facebook-f").click(function () {
"use strict";
if ($('.facebook-content').css('display') == 'none') {
    $('.fb-loader-content').addClass('loader');
    $('.facebook-content').load("http://www.google.com", function () {
        console.log('loader will be removed');
        $('.fb-loader-content').removeClass('loader');
    });
    $('.facebook-content').toggle();
} else {
    $('.facebook-content').toggle();
}

});

Here is a link to the jsfiddle

2 个答案:

答案 0 :(得分:2)

使用计数器。因此,在第一次点击它之后,它会将计数器更改为2,从而导致else条件从现在开始运行。

$(".facebook-f").click(function () {
"use strict";
var counter = 1;  // added this
if ($('.facebook-content').css('display') == 'none' && counter === 1) {  // added another condition here
    $('.fb-loader-content').addClass('loader');
    $('.facebook-content').load("http://www.google.com", function () {
        console.log('loader will be removed');
        $('.fb-loader-content').removeClass('loader');
        counter += 1; // update the counter so it changes to 2 causing the else to run the next times
    });
    $('.facebook-content').toggle();
} else {
    $('.facebook-content').toggle();
}
});

答案 1 :(得分:0)

使用@LowerClassOverflowian计数器方法和“closure”我设法制作了有效的东西。

以下是代码:

按钮

var element = document.getElementById(“facebook-f”);

element.onclick =(function(){     “使用严格”;

// init the count to 0
var count = 0;

return function(e) {
    //count
    count++;

    if (count === 1) {    // do something on first click
        $('.fb-loader-content').addClass('loader');
        $('.facebook-content').load("templates/include/scripts/facebook.php", function () {
            $('.fb-loader-content').removeClass('loader');
        });
    } 
    if (count > 1) {
        $('.facebook-content').slideToggle(200);
    }
};

})     ();

为每个帮助过的人欢呼。如果您有任何进一步的建议,请告诉我。