避免jquery范围/ init /问题/冲突的最佳实践?

时间:2019-03-17 05:07:01

标签: jquery

我很难学习构建杂项的正确方法。 javascript / jquery文件。我趋向于将函数和var并排放置,但是随着文件变大,我总是会遇到问题。

我将块向上或向下移动会破坏其他东西。我在doc ready块的末尾放置了一个简单的alert('hello');,它不起作用,但它在顶部。我尝试将这个文件放在顶部,在文档准备就绪之外的所有变量,将在文档外部准备就绪的所有函数的底部放置。

FIDDLE

var mobileMenuWrapper = $('div.mobile-menu-wrapper');
var mobileMenuToggler = $('.mobile-nav-toggle');
var mobileMailToggler = $('#mobileMailToggle');
var currentPage = $('main').attr('id');
var btnSlideLeft = $('.btn-slide-left');
var btnScrollDown = $('.btn-page-scroll');
var itemBox = $('.item-box');
var btnSquare = $('.btn-square');
var pageNavItem = $('.page-nav li');
var serviceBtn = $('.service-box .icon-loader');
var slideNum, serviceId;
var page = new fullpage(`#${currentPage}`, {
  autoScrolling: true,
  continuousHorizontal: false,
  controlArrows: false,
  dragAndMove: false,
  fixedElements: '.topbar',
  loopHorizontal: false,
  responsiveSlides: false,
  scrollingSpeed: 500,
  touchSensitivity: 5,
  verticalCentered: false,
  normalScrollElements: '#intro, #services',
  onLeave: function (index, nextIndex, direction) {
  },

  onSlideLeave: function (anchorLink, index, slideIndex, direction, nextSlideIndex) {
  },
  afterRender: function () {
  },
  afterResize: function () {
  },
  afterSlideLoad: function (anchorLink, index, slideAnchor, slideIndex) {
  },
  afterLoad: function (anchorLink, index) {
    if (index === 2 && currentPage === 'venueDetail' || index === 2 && currentPage === 'experienceDetail') {
      getSliderCount();
      $('.slide-counter').fadeIn();
    }
  },
  afterResponsive: function (isResponsive) {
  }
});
var capacitySlider = $('#venueCapacity').slider({
  range: true,
  stop: 100,
  handle: 'custom',
});
var squareFootageSlider = $('#squareFootage').slider({
  range: true,
  step: 500,
  handle: 'custom',
});
// document ready
$(function () {
   $('.fade-in').show();
  $('.use-current-location').click(function () {
    $('.rep-results').fadeIn();
  });
  $('.toggle-experience').click(function () {
    $('.map-view').toggle();
    $('.grid-view').toggle();
  });

  $('[data-toggle=popover]').popover({
    html: true,
    content: function () {
      var id = $(this).attr('id');
      return $('#popover-content-' + id).html();
    },
    title: function () {
      var title = $(this).attr('data-popover-content');
      return $(title).children('.popover-heading').html();
    }
  });

  $(document).keyup(function (e) {
    if (e.key === 'Escape') {
      $('.popover').removeClass('show');
    }
  });

  serviceBtn.click(function () {
    serviceId = $(this).prop('id');
    slideNum = serviceId.substr(serviceId.length - 1) - 1;
    console.log(slideNum);
    page.moveTo(2, slideNum);
  });

  btnSlideLeft.click(function () {
    page.moveSlideLeft();
    getSliderCount();
  });
  var btnSlideRight = $('.btn-slide-right');
  btnSlideRight.click(function () {
    page.moveSlideRight();
    getSliderCount();
  });

  $('#desktopMailToggle').click(function () {
    $('aside.sidebar').toggleClass('open');
    $(this).toggleClass('open');
  });

  mobileMenuToggler.click(function () {
    mobileMenuWrapper.toggleClass('menu-open');
    if (mobileMenuWrapper.hasClass('contact-form-showing')) {
      mobileMenuWrapper.removeClass('contact-form-showing');
      $('body').css('overflow', 'auto');
    }
  });

  mobileMailToggler.click(function () {
    mobileMenuWrapper.toggleClass('contact-form-showing');
    if (mobileMenuWrapper.hasClass('contact-form-showing')) {
      $('body').css('overflow', 'hidden');
    } else {
      $('body').css('overflow', 'auto');
    }
  });

  pageNavItem.click(function () {
    var section = $(this).index() + 1;
    page.moveTo(section);
  });

  btnScrollDown.click(function () {
    page.moveSectionDown();
  });

  btnSquare.click(function () {
    $('.btn-square').removeClass('loading');
    $(this).addClass('loading');
    $('.item-box').removeClass('selected');
    $(this).closest('.item-box').toggleClass('selected');
  });

  itemBox.click(function () {
    $('.item-box').removeClass('selected');
    $(this).addClass('selected');
  });

  capacitySlider.on('slide', function () {
    getCapacityValue();
  });

  squareFootageSlider.on('slide', function () {
    getSquareFootageValue();
  });

  getCapacityValue();
  getSquareFootageValue();

  $('#resetFilters').click(function () {
    capacitySlider.slider('refresh');
    squareFootageSlider.slider('refresh');
    $('input[type="checkbox"]').prop('checked', false);
    getCapacityValue();
    getSquareFootageValue();
  });

  $('.grid-map-toggle').click(function () {
    $('.map-view').toggle();
    $('.grid-view').toggle();

    venueResults.recalculate();
  });
  $(window).resize(function () {
    autoHeightMobile();
  });
  autoHeightMobile();

});

// functions

function autoHeightMobile() {
  var windowWidth = $(window).width();
  if (windowWidth < 768) {
    $('section.section').addClass('fp-auto-height');
  } else {
    $('section.section').removeClass('fp-auto-height');
  }
}

function getSliderCount() {
  var currentSlide;
  var slideCount;
  var total = $('.slide').length;
  var activeSlide = page.getActiveSlide();
  var index = activeSlide.index + 1;
  if (index && index < 10) {
    currentSlide = `0${index}`;
  } else {
    currentSlide = index;
  }
  if (total && total < 10) {
    slideCount = `0${total}`;
  } else {
    slideCount = total;
  }
  $('.slide-index').text(currentSlide);
  $('.slide-total').text(slideCount);
}

function getSquareFootageValue() {
  var squareFootageVal = squareFootageSlider.slider('getValue');
  if ((squareFootageVal[0] + 100) >= squareFootageVal[1]) {
  }
  $('.sf-low').text(squareFootageVal[0]);
  $('.sf-high').text(squareFootageVal[1]);
}

function getCapacityValue() {
  var capacityVal = capacitySlider.slider('getValue');
  if ((capacityVal[0] + 250) >= capacityVal[1]) {
  }
  $('.cap-low').text(capacityVal[0]);
  $('.cap-high').text(capacityVal[1]);
}

1 个答案:

答案 0 :(得分:1)

如我所见,您的代码大部分都与DOM交互。因此,如果您将所有var移出document.ready,则它将是未定义的,因为html元素尚未准备好。这意味着jQuery将无法找到“ div.mobile-menu-wrapper”,并且它将崩溃。最好将所有变量都放在顶部是一种好习惯,您已经朝着最佳做法迈出了一步。因此,如注释中所建议,您必须将所有内容移至$(document).ready(function(){})

$(function () {
    var mobileMenuWrapper = $('div.mobile-menu-wrapper');
    var mobileMenuToggler = $('.mobile-nav-toggle');
    var mobileMailToggler = $('#mobileMailToggle');
    var currentPage = $('main').attr('id');
    var btnSlideLeft = $('.btn-slide-left');
    var btnScrollDown = $('.btn-page-scroll');
    var itemBox = $('.item-box');
    var btnSquare = $('.btn-square');
    var pageNavItem = $('.page-nav li');
    var serviceBtn = $('.service-box .icon-loader');
    var slideNum, serviceId;
    var page = new fullpage(`#${currentPage}`, {
        autoScrolling: true,
        continuousHorizontal: false,
        controlArrows: false,
        dragAndMove: false,
        fixedElements: '.topbar',
        loopHorizontal: false,
        responsiveSlides: false,
        scrollingSpeed: 500,
        touchSensitivity: 5,
        verticalCentered: false,
        normalScrollElements: '#intro, #services',
        onLeave: function (index, nextIndex, direction) {
        },

        onSlideLeave: function (anchorLink, index, slideIndex, direction, nextSlideIndex) {
        },
        afterRender: function () {
        },
        afterResize: function () {
        },
        afterSlideLoad: function (anchorLink, index, slideAnchor, slideIndex) {
        },
        afterLoad: function (anchorLink, index) {
            if (index === 2 && currentPage === 'venueDetail' || index === 2 && currentPage === 'experienceDetail') {
                getSliderCount();
                $('.slide-counter').fadeIn();
            }
        },
        afterResponsive: function (isResponsive) {
        }
    });
    var capacitySlider = $('#venueCapacity').slider({
        range: true,
        stop: 100,
        handle: 'custom',
    });
    var squareFootageSlider = $('#squareFootage').slider({
        range: true,
        step: 500,
        handle: 'custom',
    });
    // document ready

        $('.fade-in').show();
        $('.use-current-location').click(function () {
            $('.rep-results').fadeIn();
        });
        $('.toggle-experience').click(function () {
            $('.map-view').toggle();
            $('.grid-view').toggle();
        });

        $('[data-toggle=popover]').popover({
            html: true,
            content: function () {
                var id = $(this).attr('id');
                return $('#popover-content-' + id).html();
            },
            title: function () {
                var title = $(this).attr('data-popover-content');
                return $(title).children('.popover-heading').html();
            }
        });

        $(document).keyup(function (e) {
            if (e.key === 'Escape') {
                $('.popover').removeClass('show');
            }
        });

        serviceBtn.click(function () {
            serviceId = $(this).prop('id');
            slideNum = serviceId.substr(serviceId.length - 1) - 1;
            console.log(slideNum);
            page.moveTo(2, slideNum);
        });

        btnSlideLeft.click(function () {
            page.moveSlideLeft();
            getSliderCount();
        });
        var btnSlideRight = $('.btn-slide-right');
        btnSlideRight.click(function () {
            page.moveSlideRight();
            getSliderCount();
        });

        $('#desktopMailToggle').click(function () {
            $('aside.sidebar').toggleClass('open');
            $(this).toggleClass('open');
        });

        mobileMenuToggler.click(function () {
            mobileMenuWrapper.toggleClass('menu-open');
            if (mobileMenuWrapper.hasClass('contact-form-showing')) {
                mobileMenuWrapper.removeClass('contact-form-showing');
                $('body').css('overflow', 'auto');
            }
        });

        mobileMailToggler.click(function () {
            mobileMenuWrapper.toggleClass('contact-form-showing');
            if (mobileMenuWrapper.hasClass('contact-form-showing')) {
                $('body').css('overflow', 'hidden');
            } else {
                $('body').css('overflow', 'auto');
            }
        });

        pageNavItem.click(function () {
            var section = $(this).index() + 1;
            page.moveTo(section);
        });

        btnScrollDown.click(function () {
            page.moveSectionDown();
        });

        btnSquare.click(function () {
            $('.btn-square').removeClass('loading');
            $(this).addClass('loading');
            $('.item-box').removeClass('selected');
            $(this).closest('.item-box').toggleClass('selected');
        });

        itemBox.click(function () {
            $('.item-box').removeClass('selected');
            $(this).addClass('selected');
        });

        capacitySlider.on('slide', function () {
            getCapacityValue();
        });

        squareFootageSlider.on('slide', function () {
            getSquareFootageValue();
        });

        getCapacityValue();
        getSquareFootageValue();

        $('#resetFilters').click(function () {
            capacitySlider.slider('refresh');
            squareFootageSlider.slider('refresh');
            $('input[type="checkbox"]').prop('checked', false);
            getCapacityValue();
            getSquareFootageValue();
        });

        $('.grid-map-toggle').click(function () {
            $('.map-view').toggle();
            $('.grid-view').toggle();

            venueResults.recalculate();
        });
        $(window).resize(function () {
            autoHeightMobile();
        });
        autoHeightMobile();



    // functions

    function autoHeightMobile() {
        var windowWidth = $(window).width();
        if (windowWidth < 768) {
            $('section.section').addClass('fp-auto-height');
        } else {
            $('section.section').removeClass('fp-auto-height');
        }
    }

    function getSliderCount() {
        var currentSlide;
        var slideCount;
        var total = $('.slide').length;
        var activeSlide = page.getActiveSlide();
        var index = activeSlide.index + 1;
        if (index && index < 10) {
            currentSlide = `0${index}`;
        } else {
            currentSlide = index;
        }
        if (total && total < 10) {
            slideCount = `0${total}`;
        } else {
            slideCount = total;
        }
        $('.slide-index').text(currentSlide);
        $('.slide-total').text(slideCount);
    }

    function getSquareFootageValue() {
        var squareFootageVal = squareFootageSlider.slider('getValue');
        if ((squareFootageVal[0] + 100) >= squareFootageVal[1]) {
        }
        $('.sf-low').text(squareFootageVal[0]);
        $('.sf-high').text(squareFootageVal[1]);
    }

    function getCapacityValue() {
        var capacityVal = capacitySlider.slider('getValue');
        if ((capacityVal[0] + 250) >= capacityVal[1]) {
        }
        $('.cap-low').text(capacityVal[0]);
        $('.cap-high').text(capacityVal[1]);
    }
});

您可以做的另一件事是使用iife(立即调用的函数)添加名称空间。您可以here来了解它。

        let helper = (function ($) {
        let autoHeightMobile = function () {
            var windowWidth = $(window).width();
            if (windowWidth < 768) {
                $('section.section').addClass('fp-auto-height');
            } else {
                $('section.section').removeClass('fp-auto-height');
            }
        };

        let getSliderCount = function () {
            var currentSlide;
            var slideCount;
            var total = $('.slide').length;
            var activeSlide = page.getActiveSlide();
            var index = activeSlide.index + 1;
            if (index && index < 10) {
                currentSlide = `0${index}`;
            } else {
                currentSlide = index;
            }
            if (total && total < 10) {
                slideCount = `0${total}`;
            } else {
                slideCount = total;
            }
            $('.slide-index').text(currentSlide);
            $('.slide-total').text(slideCount);
        };

        let getSquareFootageValue = function () {
            var squareFootageVal = squareFootageSlider.slider('getValue');
            if ((squareFootageVal[0] + 100) >= squareFootageVal[1]) {
            }
            $('.sf-low').text(squareFootageVal[0]);
            $('.sf-high').text(squareFootageVal[1]);
        };

        let getCapacityValue = function () {
            var capacityVal = capacitySlider.slider('getValue');
            if ((capacityVal[0] + 250) >= capacityVal[1]) {
            }
            $('.cap-low').text(capacityVal[0]);
            $('.cap-high').text(capacityVal[1]);
        };
        return {
            autoHeightMobile,
            getSliderCount,
            getCapacityValue,
            getSquareFootageValue
        }
    })(jQuery)


    let app = (function ($) {

        let run = function () {
            var mobileMenuWrapper = $('div.mobile-menu-wrapper');
            var mobileMenuToggler = $('.mobile-nav-toggle');
            var mobileMailToggler = $('#mobileMailToggle');
            var currentPage = $('main').attr('id');
            var btnSlideLeft = $('.btn-slide-left');
            var btnScrollDown = $('.btn-page-scroll');
            var itemBox = $('.item-box');
            var btnSquare = $('.btn-square');
            var pageNavItem = $('.page-nav li');
            var serviceBtn = $('.service-box .icon-loader');
            var slideNum, serviceId;
            var page = new fullpage(`#${currentPage}`, {
                autoScrolling: true,
                continuousHorizontal: false,
                controlArrows: false,
                dragAndMove: false,
                fixedElements: '.topbar',
                loopHorizontal: false,
                responsiveSlides: false,
                scrollingSpeed: 500,
                touchSensitivity: 5,
                verticalCentered: false,
                normalScrollElements: '#intro, #services',
                onLeave: function (index, nextIndex, direction) {
                },

                onSlideLeave: function (anchorLink, index, slideIndex, direction, nextSlideIndex) {
                },
                afterRender: function () {
                },
                afterResize: function () {
                },
                afterSlideLoad: function (anchorLink, index, slideAnchor, slideIndex) {
                },
                afterLoad: function (anchorLink, index) {
                    if (index === 2 && currentPage === 'venueDetail' || index === 2 && currentPage === 'experienceDetail') {
                        helper.getSliderCount();
                        $('.slide-counter').fadeIn();
                    }
                },
                afterResponsive: function (isResponsive) {
                }
            });
            var capacitySlider = $('#venueCapacity').slider({
                range: true,
                stop: 100,
                handle: 'custom',
            });
            var squareFootageSlider = $('#squareFootage').slider({
                range: true,
                step: 500,
                handle: 'custom',
            });
            // document ready

            $('.fade-in').show();
            $('.use-current-location').click(function () {
                $('.rep-results').fadeIn();
            });
            $('.toggle-experience').click(function () {
                $('.map-view').toggle();
                $('.grid-view').toggle();
            });

            $('[data-toggle=popover]').popover({
                html: true,
                content: function () {
                    var id = $(this).attr('id');
                    return $('#popover-content-' + id).html();
                },
                title: function () {
                    var title = $(this).attr('data-popover-content');
                    return $(title).children('.popover-heading').html();
                }
            });

            $(document).keyup(function (e) {
                if (e.key === 'Escape') {
                    $('.popover').removeClass('show');
                }
            });

            serviceBtn.click(function () {
                serviceId = $(this).prop('id');
                slideNum = serviceId.substr(serviceId.length - 1) - 1;
                console.log(slideNum);
                page.moveTo(2, slideNum);
            });

            btnSlideLeft.click(function () {
                page.moveSlideLeft();
                helper.getSliderCount();
            });
            var btnSlideRight = $('.btn-slide-right');
            btnSlideRight.click(function () {
                page.moveSlideRight();
                helper.getSliderCount();
            });

            $('#desktopMailToggle').click(function () {
                $('aside.sidebar').toggleClass('open');
                $(this).toggleClass('open');
            });

            mobileMenuToggler.click(function () {
                mobileMenuWrapper.toggleClass('menu-open');
                if (mobileMenuWrapper.hasClass('contact-form-showing')) {
                    mobileMenuWrapper.removeClass('contact-form-showing');
                    $('body').css('overflow', 'auto');
                }
            });

            mobileMailToggler.click(function () {
                mobileMenuWrapper.toggleClass('contact-form-showing');
                if (mobileMenuWrapper.hasClass('contact-form-showing')) {
                    $('body').css('overflow', 'hidden');
                } else {
                    $('body').css('overflow', 'auto');
                }
            });

            pageNavItem.click(function () {
                var section = $(this).index() + 1;
                page.moveTo(section);
            });

            btnScrollDown.click(function () {
                page.moveSectionDown();
            });

            btnSquare.click(function () {
                $('.btn-square').removeClass('loading');
                $(this).addClass('loading');
                $('.item-box').removeClass('selected');
                $(this).closest('.item-box').toggleClass('selected');
            });

            itemBox.click(function () {
                $('.item-box').removeClass('selected');
                $(this).addClass('selected');
            });

            capacitySlider.on('slide', function () {
                helper.getCapacityValue();
            });

            squareFootageSlider.on('slide', function () {
                helper.getSquareFootageValue();
            });

            helper.getCapacityValue();
            helper.getSquareFootageValue();

            $('#resetFilters').click(function () {
                capacitySlider.slider('refresh');
                squareFootageSlider.slider('refresh');
                $('input[type="checkbox"]').prop('checked', false);
                helper.getCapacityValue();
                helper.getSquareFootageValue();
            });

            $('.grid-map-toggle').click(function () {
                $('.map-view').toggle();
                $('.grid-view').toggle();

                venueResults.recalculate();
            });
            $(window).resize(function () {
                helper.autoHeightMobile();
            });
            helper.autoHeightMobile();

        };
        return {
            run
        }

    })(jQuery);



    $(function () {
        app.run();
    });

因此,这里的helper和app有两个名称空间。助手将保留您功能块中的所有功能。应用将拥有所有document.ready内容。现在,您的变量没有全局公开,只能在app.run方法中访问。请确保此脚本文件应包含在jQuery文件或CDN链接下方。这将确保$被定义。作为标准做法,请始终确保所有JS(包括jQuery)文件都应包含在html文档的body标签末尾。