javascript - 多次使用相同 jQuery 函数的问题

标签 javascript jquery html

刚刚开始 FE Web 开发。我发现了我非常喜欢的这个图像查看器。让它可以处理我的文件。但是,我在同一个 HTML 文件中多次使用同一个图像查看器时遇到问题。谁能指出我做错了什么?

HTML:

<div id="slider">
    <h3>EventGlance UI Mock Ups</h3>
    <a href="#" class="control_next">></a>
    <a href="#" class="control_prev"><</a>
    <ul>
      <li><img src="images/1.jpg" height="568" width="320" /></li>
      <li><img src="images/2.jpg" height="568" width="320" /></li>
      <li><img src="images/3.jpg" height="568" width="320" /></li>
      <li><img src="images/4.jpg" height="568" width="320" /></li>
    </ul>  
</div>

JQuery/JS:

jQuery(document).ready(function ($) {
    var slideCount = $('#slider ul li').length;
    var slideWidth = $('#slider ul li').width();
    var slideHeight = $('#slider ul li').height();
    var sliderUlWidth = slideCount * slideWidth;

    $('#slider').css({ width: slideWidth, height: slideHeight });

    $('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });

    $('#slider ul li:last-child').prependTo('#slider ul');

    function moveLeft() {
        event.preventDefault(); 
        $('#slider ul').animate({
            left: + slideWidth
        }, 200, function () {
            $('#slider ul li:last-child').prependTo('#slider ul');
            $('#slider ul').css('left', '');
        });
    };

    function moveRight() {
        event.preventDefault(); 
        $('#slider ul').animate({
            left: - slideWidth
        }, 200, function () {
            $('#slider ul li:first-child').appendTo('#slider ul');
            $('#slider ul').css('left', '');
        });
    };

    $('a.control_prev').click(function () {
        moveLeft();
    });

    $('a.control_next').click(function () {
        moveRight();
    });

});

最佳答案

您将无法在同一页面上使用此 slider 的多个版本,因为它专门针对#slider,ID 是唯一的,这会导致问题。

我建议使用类似Owl Carousel的东西它在 GitHub 上非常受 3500 多颗星的欢迎,您可以轻松地将其设置为目标类名,并且比将代码重写到插件中要容易得多。

如果您确实想使用现有代码,最好的选择是将其转换为插件,该插件会将代码应用于您选择的所有元素,但您必须删除对 #slider 的引用并执行您循环的元素上下文中的所有内容。

<小时/>

如何将其整合到插件中的示例如下:

(function( $ ) {

    // Your slider plugin, $(selector).slider();
    $.fn.slider = function() {

        // Rather than target a single element, this will take one
        // or more results from your selector and loop over it
        return this.each(function() {

            // $self will now be the equivalent of #slider
            // in your demo code, everything else selected
            // will use it as context
            var $self = $(this),
                $list = $self.find('ul'),
                $listItems = $list.find('li'),

                // Your original variables
                slideCount = $listItems.length,
                slideWidth = $listItems.width(),
                slideHeight = $listItems.height(),
                sliderUlWidth = slideCount * slideWidth;

            // $self now references .slider
            $self.css({ width: slideWidth, height: slideHeight });

            // $list now references .slider > ul
            $list.css({ width: sliderUlWidth, left: 0 });

            // .find is quicker than context, use $list to find
            // last child
            $list.find('li:last-child').prependTo( $list );

            // No need for functions as there's no re-use going on,
            // also in your demo event.preventDefault did nothing
            $self.find('a.control_prev').on('click', function (e) {
                e.preventDefault(); 
                $list.animate({
                    left: + slideWidth
                }, 200, function () {
                    $list.find('li:last-child').prependTo( $list );
                    $list.css('left', '');
                });
            });

            // Once again, no need for function especially when you
            // weren't passing your event object through anyway
            $self.find('a.control_next').on('click', function (e) {
                e.preventDefault(); 
                $list.animate({
                    left: - slideWidth
                }, 200, function () {
                    $list.find('li:first-child').appendTo( $list );
                    $list.css('left', '');
                });
            });
        });

    };

}( jQuery ));

// Usage example:
$( ".slider" ).slider();
<小时/>

我已经用一些演示 HTML 和 CSS 为您构建了一个基本插件(我假设您应用了演示中未包含的样式)。您可以在这里查看 jsfiddle:

https://jsfiddle.net/71j5psr0/31/

关于javascript - 多次使用相同 jQuery 函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33839254/

相关文章:

javascript - 在不使用 html5mode 的情况下使用 AngularJS 解析查询字符串的最佳方法

javascript - 用JS关闭汉堡菜单

html - Bootstrap 3 col-sm-4 创建两列而不是 3

javascript - 通过 Ajax 成功函数传递参数

javascript - 为什么要在 Array.prototype.forEach() 中检查 null?

javascript - 创建 websocket 时如何禁用 Header 中的 cookie?

javascript - 没有 childList 的 MutationObserver characterData 使用

javascript - 基于 Next Prev 值的 jQuery 验证

javascript - Google Geocoding - 抓取地址和坐标

html - 图像不会与父 div 中的文本内联显示