jQuery var在传入.click()时变为未定义

时间:2018-06-06 19:58:25

标签: javascript jquery slider

我正在使用没有大纲库或插件从头开始构建一个愚蠢的简单jQuery图像滑块。我是jQuery的新手,但我遇到了一个看起来很简单的bug。

我在.click()函数之外定义一个var,然后当我尝试在.click()中调用该var时,它被认为是未定义的。奇怪的是我可以召唤其他变种。有什么想法吗?

Here is a fiddle of the slider

这是HTML:

<div class="slider">
        <ul>
            <li><img class="slide img-fluid" src="http://via.placeholder.com/1000x500?text=1"></li>
            <li><img class="slide img-fluid" src="http://via.placeholder.com/1000x500?text=2"></li>
            <li><img class="slide img-fluid" src="http://via.placeholder.com/1000x500?text=3"></li>
            <li><img class="slide img-fluid" src="http://via.placeholder.com/1000x500?text=4"></li>
            <li><img class="slide img-fluid" src="http://via.placeholder.com/1000x500?text=5"></li>
        </ul>
        <span id="prev">&#8698;</span>
        <span id="next">&#8699;</span>
    </div>

这是JS

// Set Targets
var next = $('#next');
var prev = $('#prev');
var slides = $('.slider ul')

// Build the var to animate the length of the img
var imgWidth = "-=" + ($('.slider img').first().width());
// Find number of imgs
var numOfSlides = $('.slider ul li').length;
// Set Slidecount to 1
var slideCount = 1; 

// When next btn is clicked
next.click(function(){

    // Check vars in console
    console.log(numOfSlides + " Slides");
    console.log(slideCount); <-------------- This is being marked as undefined

    // Check to see if there are more slides
    if (slideCount < numOfSlides) {
        // Slide the images
        slides.animate({'margin-left': imgWidth}, 1000);
        // Add one to slide count
        slideCount++;
    // If there are no more images, reset margin to 0 and return to first
    } else {
        // Animate margin to 0
        slides.animate({'margin-left': 0}, 1000);
        // Resent counter to 1
        var slideCount = 1;
    }
});

当我点击下一个箭头时,我看到它在控制台中打印出来 - 这很奇怪,因为numOfSlides显示为有值,但不是幻灯片。

Screenshot of Console l

修改: 当我正在构建小提琴时,我看到这个错误弹出说我的var超出了范围?但是为什么其他var会在这个函数内部工作呢? JS Fiddle Screenshot

4 个答案:

答案 0 :(得分:3)

在您的点击功能中,您正在重新定义slideCount,因此这个新功能将在功能内部使用,而不是在外部使用。

undefined变量为console.log的原因是hoisting mechanism:每个声明都会显示在范围的开头。

因此编译器的代码看起来像

next.click(function(){
    var slideCount;  <----- hoisted here, value is undefined for now
    console.log(slideCount); <------- This is still undefined

    // Check to see if there are more slides
    if (slideCount < numOfSlides) {
        // ...
        // Add one to slide count
        slideCount++; <----- like undefined++
    } else {
        // ...
        // Resent counter to 1
        slideCount = 1; <---- initialized for the first time
    }
});

答案 1 :(得分:0)

请勿在其他情况下初始化slideCount只需在var之前删除slideCount

  

当您在本地范围内再次初始化同一变量时   变量从当前范围中删除并重新初始化(这是有限的   到else范围它将始终在其他地方打印undefined)

$(document).ready(function(){

    // SLDIER

    // Set Targets
    var next = $('#next');
    var prev = $('#prev');
    var slides = $('.slider ul')

    // Build the var to animate the length of the img
    var imgWidth = "-=" + ($('.slider img').first().width());
    // Find number of imgs
    var numOfSlides = $('.slider ul li').length;
    // Set Slidecount to 1
    var slideCount = 1;

    // When next btn is clicked
    next.click(function(){

        // Check vars
        // What's strange is the numOfSlides are printing
        // But slideCount is considered undefined. Why?
        console.log(numOfSlides + " Slides");
        console.log(slideCount);

        // Check to see if there are more slides
        if (slideCount < numOfSlides) {
            // Slide the images
            slides.animate({'margin-left': imgWidth}, 1000);
            // Add one to slide count
            slideCount++;
        // If there are no more images, reset margin to 0 and return to first
        } else {
            // Animate margin to 0
            slides.animate({'margin-left': 0}, 1000);
            // Resent counter to 1
             slideCount = 1;
        }
    });
});
.slider {
    margin: 20px 0;
    margin: auto;
    height: 500px;
    max-width: 1000px;
    position: relative;
    overflow: hidden;
}
.slider ul {
    margin: 0;
    padding: 0;
    list-style: none;
    width: 9999px;
}
.slider li {
    float: left;
}
.slider #next,
.slider #prev {
    position: absolute;
    font-size: 50px;
    top: 50%;
    transform: translateY(-50%);
    color: white;
}
.slider #next {
    right: 2%;
}
.slider #prev {
    left: 2%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider">
        <ul>
            <li><img class="slide img-fluid" src="http://via.placeholder.com/1000x500?text=1"></li>
            <li><img class="slide img-fluid" src="http://via.placeholder.com/1000x500?text=2"></li>
            <li><img class="slide img-fluid" src="http://via.placeholder.com/1000x500?text=3"></li>
            <li><img class="slide img-fluid" src="http://via.placeholder.com/1000x500?text=4"></li>
            <li><img class="slide img-fluid" src="http://via.placeholder.com/1000x500?text=5"></li>
        </ul>
        <span id="prev">&#8698;</span>
        <span id="next">&#8699;</span>
    </div>

答案 2 :(得分:0)

问题是您通过使用此处的slideCount关键字重新设置点击处理程序来var

else {
        // Animate margin to 0
        slides.animate({'margin-left': 0}, 1000);
        // Resent counter to 1
        var slideCount = 1; // <-- here
    }

如果你删除它,它可以工作,因为浏览器现在&#34;知道&#34;您指的是同一个变量,无论其范围如何:

https://jsfiddle.net/hzu05xL4/

未定义,因为它仅在该范围内的后续路线中创建。其他变量很好,因为它们没有在该范围内重新创建

答案 3 :(得分:0)

你的var是undefined因为:

var a = 1; //-> defined at the top of global code
a = 2;
console.log(a); //2 

(function(){
console.log(a);//undefined 
var a = 3;  // -> at a top of function code but undefined till now  
})();

如果删除var,则可以使用之前的var定义。未定义,因为在执行任何代码之前处理声明,var声明也是作用域的(在这种情况下,第二个声明仅存在于函数内)。稍后会处理= 3。 var声明的范围也是