简体   繁体   English

如何仅在需要时运行 jQuery 函数?

[英]How can I run a jQuery function only when it's needed?

I've run into a problem where I have a responsive slider running on my site which has been added to an external .js file.我遇到了一个问题,我的网站上运行了一个响应式滑块,该滑块已添加到外部 .js 文件中。 I am running into an issue with a modal not popping up on the homepage because the page is looking for the slider which is only included on a couple of sub pages.我遇到了一个模态没有在主页上弹出的问题,因为该页面正在寻找仅包含在几个子页面中的滑块。

Chrome console is showing the following error: Uncaught TypeError: undefined is not a function Chrome 控制台显示以下错误: Uncaught TypeError: undefined is not a function

Here is my current code:这是我当前的代码:

$('.my-carousel').slick({
    speed: 330,
    slidesToShow: 4,
});

You can check if plugin has been loaded like this (it checks if given jQuery function exists):您可以像这样检查插件是否已加载(它检查是否存在给定的 jQuery 函数):

if ($().slick) {
 // .. your code
}

or或者

if ($.fn.slick) {
 // .. your code
}

You can just check if the carousel exists before calling the function like so:您可以在调用函数之前检查轮播是否存在,如下所示:

var myCarousel = $('.my-carousel');
if (typeof myCarousel.slick !== 'undefined') {
  myCarousel.slick({speed: 330, slidesToShow: 4});
}

您可以使用length来检查它是否存在,例如:

if ($('.my-element').length) { //do stuff }

You can apply slick only if it is not applied, doing something like below:仅在未应用时才可以应用 slick,执行如下操作:

$('.my-carousel').not('.slick-initialized').slick({
  // Your settings here.
});
if($('.my-carousel').length){
   $('.my-carousel').slick({
      speed: 330,
      slidesToShow: 4,
   });
}

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

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