Jquery On() 'click' working on every thing?

别等时光非礼了梦想. 提交于 2019-12-11 04:21:31

问题


Hello I have a problem which drive me crazy :( couldnt figure it out why

here is my HTML and Mustache

<section id="slideShow">
    <script id="slideShow-template" type="text/template">
        <ul>
            {{#slideShow}}
            <li class="{{{class}}}">
                <img src="{{{img}}}" alt="{{{title}}}">
                <a href="{{{link}}}">
                    <h1 class="slideShowTitle">{{title}}</h1>
                    <p class="slideShowDate">{{date}}</p>
                    <p class="slideShowDetail">{{detail}}</p>
                </a>
            </li>
            {{/slideShow}}
        </ul>
        <nav>
            {{#slideShow}}
                <a href="javascript:;"></a>
            {{/slideShow}}
        </nav>
        <a href="javscript:void(0)" class="prevSlide"></a>
        <a href="javscript:void(0)" class="nextSlide"></a>

    </script>
</section>

and here is the JS

(function() {

    var slideShow = {
        slideShow: [
        ],

        init: function() {
            this.cacheDom();
            this.bindEvents();
            this.render();
        },

        bindEvents: function() {
            this.$el.on('click', this.$next, function(){
                alert('sdsd')
            })
        },

        render: function() {
            var data = {
                slideShow: this.slideShow
            };
            this.$el.html(Mustache.render(this.template, data));
        },

        cacheDom: function() {
            this.$el = $('#slideShow');
            this.$ul = this.$el.find('ul');
            this.$li = this.$ul.find('li');
            this.$nav = this.$el.find('nav');
            this.$a = this.$nav.find('a');
            this.$next = this.$el.find('.nextSlide');
            this.$prev = this.$el.find('.prevSlide');
            this.template = $('#slideShow-template').html();
        }

    };

    slideShow.init();

})();

as you see with bindEvents(), Im trying to bind click function to the dynamically generated .nextSlide tag but it works on whole parent(#slideShow) what do I missing?

THE FIDDLE


回答1:


Change this:

    this.$el.on('click', this.$next, function(){
        alert('sdsd')
    })

to this:

    this.$el.on('click', '.nextSlide', function(){
        alert('sdsd')
    })


来源:https://stackoverflow.com/questions/53601023/jquery-on-click-working-on-every-thing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!