简体   繁体   English

如何防止jQuery函数重复?

[英]How to prevent repeat in jQuery function?

I have a simple jQuery function as 我有一个简单的jQuery函数

$('.button').click(function(){
   $("#target").slideToggle().load('http://page');
});

By slideToggle behavior, every click cause a slide, but the problem is that it will load url again too. 通过slideToggle行为,每次点击都会导致幻灯片,但问题是它会再次加载url

How can I limit the load() function to be performed only once, but slideToggle() on every click. 如何限制load()函数只执行一次,但每次点击都会执行slideToggle() In other words, how to prevent load() (only load, not the entire function) in the subsequent clicks? 换句话说,如何在后续点击中阻止load() (仅加载,而不是整个函数)?

Have a variable (global) which says whether it has been loaded or not. 有一个变量(全局),表示它是否已被加载。 Eg: 例如:

var loaded = false;
$('.button').click(function(){
   if(!loaded){
      $('#target').load('http://page');
      loaded = true;
   }
   $("#target").slideToggle();
});

This will cause the slideToggle to occur on every click, but the page to load only the once. 这将导致每次点击都会发生slideToggle,但页面只会加载一次。 :) :)

$('.button')
    .on('click.loadPage', function() {
        $("#target").load('http://page');
        $(this).off("click.loadPage");
    })
    .on('click.slideToggle', function(){
        $("#target").slideToggle();
    });

and another way without global vars: 以及没有全球变量的另一种方式:

$('.button')
    .on('click', function() {
        if ( !$(this).data("loaded") ) {
            $("#target").load('http://page');
            $(this).data("loaded", true);
        }
        $("#target").slideToggle();
    });

a simple way to get only the last action is to use the stop method before the desired method : 获取最后一个动作的简单方法是在所需方法之前使用stop方法:

$('.button').click(function(){
   $("#target").stop().slideToggle().load('http://page');
});

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

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