简体   繁体   English

jQuery中的slideUp方法遇到麻烦

[英]having trouble with the slideUp method in jquery

I am using a show hide slider which works for the slide down but doesn't respond for the slide up, can anyone explain where Im going wrong with this: 我正在使用一个显示隐藏滑块,该滑块可用于向下滑动,但对向上滑动不响应,任何人都可以解释我在哪里出错了:

var moreServicesList = $('#more-services-list').hide();

$('#more-services').on('click', function(e) {
    var flag = 0;
    if( flag === 0) {
        flag = 1;
        moreServicesList.slideDown('slow');
        $(this).html('Hide');
    } else {
        moreServicesList.slideUp('slow');
        $(this).html('Show');
        flag = 0;       
    }
    e.preventDefault();
}); 

Thanks in advance Kyle 预先感谢凯尔

You have to move var flag = 0; 您必须移动var flag = 0; outside of the event listener - http://jsfiddle.net/Nnhz8/ 在事件侦听器之外-http: //jsfiddle.net/Nnhz8/

var moreServicesList = $('#more-services-list');
var flag = 0;

$('#more-services').on('click', function(e) {

    if( flag == 0) {
        moreServicesList.slideDown('slow');
        flag = 1;
        $(this).html('Hide');
    } else {
        moreServicesList.slideUp('slow');
        $(this).html('Show');
        flag = 0;       
    }
    e.preventDefault();
});

you can use the toggle method for this like 您可以为此使用toggle方法

$('#more-services').on('toggle', function(e) {
        $('#more-services-list').slideDown('slow');
        $(this).html('Hide');
    } function(){
        $('#more-services-list').slideUp('slow');
        $(this).html('Show');   
    }
});

var flag every time initializes to 0 in your case 每次您的情况下var标志每次初始化为0

You're resetting your flag each time the event handler is called: 你每一个事件处理程序被调用时重置标志:

$('#more-services').on('click', function(e) {
    var flag = 0;
}

To fix this, move the flag declaration in front of the event handler: 要解决此问题,请将标志声明移到事件处理程序的前面:

var flag = 0;
$('#more-services').on('click', function(e) {}

Here's a working example: http://jsfiddle.net/wMNtT/ 这里有一个工作示例: http://jsfiddle.net/wMNtT/

Because you define your flag inside the function. 因为您在函数内定义了flag It resets to zero every time the function is called. 每次调用该函数时,它将重置为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM