简体   繁体   English

使JQuery下拉代码可重复使用

[英]Making JQuery Drop Down Code Re-usable

I've found a drop down on Codrops that I'd like to use in my application - it's example #5 on this page: https://tympanus.net/codrops/2012/10/04/custom-drop-down-list-styling/ 我找到了要在我的应用程序中使用的Codrops的下拉列表-此页面上的示例#5: https : //tympanus.net/codrops/2012/10/04/custom-drop-down-列表样式/

I've popped it onto my page with the CSS and and the JS and it works and looks good etc, but when I've started to add another one and realized that it's not going to work because the code is engineered to only work for one drop down and to make it work for multiple I'd have to duplicate the JS code which I'm not keen to do and standards wise it's not the right way of doing it. 我已经使用CSS和JS将其弹出到页面上,并且可以正常工作,但是看起来不错,但是当我开始添加另一个时,我意识到它不起作用,因为代码被设计为仅适用于一个下拉列表并使其适用于多个应用程序,我必须复制我不愿做的JS代码,并且从标准的角度来看,这不是正确的做法。

I'me just not sure how I can create something that will pass in the dropdowns and set click events for each of them as in production most of these boxes are going to come onto the page dynamically. 我只是不确定我如何创建将在下拉列表中传递的内容并为每个下拉列表设置点击事件,因为在生产中,大多数这些框都会动态出现在页面上。

I've created a fiddle of the dropdown and the code I'm using here: https://jsfiddle.net/WebDevelopWolf/jou30bvg/ 我已经创建了下拉菜单和此处使用的代码的小提琴: https : //jsfiddle.net/WebDevelopWolf/jou30bvg/

And the JS part of the code is (this is in the fiddle too): 代码的JS部分是(这也在小提琴中):

function DropDown(el) {
    this.dd = el;
    this.initEvents();
}
DropDown.prototype = {
    initEvents : function() {
        var obj = this;

        obj.dd.on('click', function(event){
            $(this).toggleClass('active');
            event.stopPropagation();
        }); 
    }
}

$(function() {
    var dd = new DropDown( $('#dd') );
    $(document).click(function() {
        // all dropdowns
        $('.wrapper-dropdown-5').removeClass('active');
    });
});

All I did was to cut a bit from your code and it can be reused. 我所做的只是从您的代码中减少了一点,可以重复使用。

function DropDown(el) {
    el.on('click', function(event){
      $(this).toggleClass('active');
      event.stopPropagation();
    }); 
}


new DropDown( $('#dd') );

here Is a fiddle https://jsfiddle.net/jou30bvg/3/ 这是一个小提琴https://jsfiddle.net/jou30bvg/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM