如何避免jquery多次将对象初始化为函数

问题描述 投票:1回答:1

我将对象初始化为smartphoto,如下所示

$(".js_smartphoto").SmartPhoto();

如果用户单击分页按钮,则代码将在内部循环

    through all list and assign then function again. Right now the object already assigned will be assigned again, so the smartphoto will appear twice.

    有没有办法可以检查$(“。js_smartphoto”)是否已经分配了SmartPhoto()?所以它可以避免重复分配。也许代码谎言这个?

    if($(".js_smartphoto").SmartPhoto() == false)
    {
       $(".js_smartphoto").SmartPhoto();
    }
    

    或者另一种方式,我可以先破坏功能,然后重新初始化。像这样?

    $(".js_smartphoto").SmartPhoto().destroy();
    $(".js_smartphoto").SmartPhoto();
    
    jquery
    1个回答
    1
    投票

    正如它在SmartPhoto documentation中显示的那样,您可以像这样初始化SmartPhoto图像查看器:

    var mySmartPhoto = new SmartPhoto(".js-smartPhoto");
    

    另外,正如您在每个文档中看到的那样,没有销毁方法。 在你的情况下你可以做什么:

    // the top of the page
    var mySmartPhoto = new SmartPhoto(".js-smartPhoto");
    
    // ... the rest of the code/page
    
    if (typeof mySmartPhoto === 'object') {
        // SmartPhoto was already initialized
    }
    
    © www.soinside.com 2019 - 2024. All rights reserved.