jQuery插件无法识别.next()

时间:2017-07-20 06:35:06

标签: javascript jquery html plugins

我尝试创建一个简单的幻灯片插件,但它声明.next()不是一个函数。

未捕获TypeError:currSlider.next不是函数 在变化(jquery.methodSlider.js:11)

(function ( $ ) {

$('.res-slideshow').methodSlider({
    speed:3000
});
$.fn.methodSlider = function(options) {
    var settings = $.extend({
        speed:1000
    },options);
    this.find('li:first').addClass('top');

    var change = function(){
        var currSlider = this.find('li.top');
        //This doesnt work.
        var nextSlider = currSlider.next();

        nextSlider.addClass('top');
        currSlider.removeClass('top');
    }
    setInterval(change, settings.speed);
    return this;
};

}( jQuery ));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="residence-slider">
    <ul class="res-slideshow">
        <li>
          <img src="img/site_images/home-01.jpg" alt="This is image 1">
        </li>
        <li>
          <img src="img/site_images/home-02.jpg" alt="This is image 2">
        </li>
        <li>
          <img src="img/site_images/home-03.jpg" alt="This is image 3">
        </li>            
    </ul>
</div>

1 个答案:

答案 0 :(得分:1)

正如安德烈亚斯所说,问题来自你的这个利用。

这个不是dom元素,因为你使用它,在jQuery中,你必须先添加一个 $ ,所以它是 $(this)获得元素。

在您的情况下,由于不是元素, next()函数不可用。

我在下面更新了您的代码:

(function ( $ ) {


$.fn.methodSlider = function(options) {
    var settings = $.extend({
        speed:1000
    },options);
    $(this).find('li:first').addClass('top');
    
    var that = $(this);
    var change = function(){
        var currSlider = that.find('li.top');
        var nextSlider = currSlider.next();

        nextSlider.addClass('top');
        currSlider.removeClass('top');
    }
    setInterval(change, settings.speed);
    return this;
};

$('.res-slideshow').methodSlider({
    speed:3000
});

}( jQuery ));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="residence-slider">
    <ul class="res-slideshow">
        <li>
          <img src="img/site_images/home-01.jpg" alt="This is image 1">
        </li>
        <li>
          <img src="img/site_images/home-02.jpg" alt="This is image 2">
        </li>
        <li>
          <img src="img/site_images/home-03.jpg" alt="This is image 3">
        </li>            
    </ul>
</div>