我有一个带有jquery代码的文件,我把它连接到两个不同的页面,因为一页代码的一部分,另一页的代码。但第二页的代码不起作用,jquery在第一页的代码中抛出错误。但是第一页上有相同代码没有错误。 第二页错误:
Uncaught TypeError: $(...).slick is not a function
at runSlick (script.js:15)
at HTMLDocument.<anonymous> (script.js:19)
at mightThrow (jquery-3.2.1.js:3583)
at process (jquery-3.2.1.js:3651)
jquery的:
$(document).ready(function () {
//CODE FOR THE FIRST PAGE
//Main Slider
var maxWidth = 992,
slickVar = {
dots: true,
responsive: [
{
breakpoint: maxWidth,
settings: 'unslick'
}
]
},
runSlick = function() {
$('.sl').slick(slickVar);
};
// slick initialization while document ready
runSlick();
// listen to jQuery's window resize
$(window).on('resize', function(){
var width = $(window).width();
if(width < maxWidth) {
// reinit slick while window's width is less than maximum width (992px)
runSlick();
}
}).resize();
//hide slider elements if window's width is less than maximum width (992px)
$(window).on('resize', function(){
if ($(this).width() < maxWidth) {
$('.hidden').addClass('d-none');
} else {
$('.hidden').removeClass('d-none');
}
}).resize();
//Slider in clients section
$('.sl-2').slick({
infinite: true,
slidesToShow: 7,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 1500,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 3,
infinite: true,
autoplay: true,
autoplaySpeed: 1500
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 1500
}
}
]
});
//show image on hover over features-list element
$('.features-list li>.feature-top').hover(
function() {
$(this).find('.top-wrapper').addClass('d-none');
$(this).css({
'padding': '0',
'background-color': '#f5f5f5'
});
$(this).find('.hover-content').fadeIn('slow');
},
function() {
$(this).find('.top-wrapper').removeClass('d-none');
$(this).css({
'padding': '20px 0',
'background-color': '#ffea00'
});
$(this).find('.hover-content').fadeOut(50);
}
);
//Isotope in works section
$('.grid').isotope({
// main isotope options
itemSelector: '.grid-item',
masonry: {
columnWidth: 15,
isFitWidth: true
}
});
//END OF CODE FOR THE FIRST PAGE
//CODE FOR THE SECOND PAGE
$(".portfolio-menu-link").click(function () {
$(".portfolio-menu-link").removeClass("active-portfolio-link");
$(this).addClass("active-portfolio-link");
});
});
答案 0 :(得分:2)
我只在第一页上有光滑的()而在另一页上没有。是否意味着我需要为第二页提供另一个jquery文件?
是。任何包含jQuery代码的页面都需要它,因为你引用它。它未在页面上使用的事实是无关紧要的。 jQuery引用它,因此需要加载它。
如果你想检查你在DOM中是否存在调用Slick Slider的元素(为了避免将jQuery分成每个页面的多个文件),你可以这样做:
var $sl2 = $('.sl-2');
if ($sl2.length) {
$sl2.slick({
infinite: true,
// settings...
});
}