如何解决“自定义下拉列表”项的选择

时间:2019-05-03 10:42:35

标签: javascript jquery list drop-down-menu

我已使用以下网站的自定义下拉列表:https://tympanus.net/Tutorials/CustomDropDownListStyling/index3.html

我已经对其进行了自定义,并在一页中使用了两种形式。

当前问题:
1.使用两种形式时,选择两种形式都适用。

问题:
1.如何修复jQuery代码,以使从表单中进行选择的行为表现为个人,而不将其应用于两者?
2.有什么更好的方法可以自定义“选择表单”,而不是使用无序列表,并且可以在所有浏览器上使用吗?

Codepen:https://codepen.io/lukas_kocka/pen/axeeOo

Java脚本:

function DropDown(el) {
    this.dd = el;
    this.placeholder = this.dd.children('span');
    this.opts = this.dd.find('ul.dropdown > li');
    this.val = '';
    this.index = -1;
    this.initEvents();
}
DropDown.prototype = {
    initEvents: function () {
        var obj = this;

        obj.dd.on('click', function (event) {
            $('.wrapper-dropdown-3').not(this).removeClass('active');
            $(this).toggleClass('active');
            return false;
        });

        obj.opts.on('click', function () {
            var opt = $(this);
            obj.val = opt.text();
            obj.index = opt.index();
            obj.placeholder.text(obj.val);
        });
    },
    getValue: function () {
        return this.val;
    },
    getIndex: function () {
        return this.index;
    }
}

$(function () {

    var dd = new DropDown($('.wrapper-dropdown-3'));

    $(document).click(function () {
        // all dropdowns
        $('.wrapper-dropdown-3').removeClass('active');
    });

});

我希望在选择项目时,两种形式都可以作为一个个体使用。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

问题1: 发生此问题是因为两个下拉列表都具有相同的id =“ dd” class =“ wrapper-dropdown-3”

我认为您可以按以下方式修复它:

HTML:将第二个下拉列表的ID更改为“ dd1”

<div id="dd" class="wrapper-dropdown-3" tabindex="1">
<div id="dd1" class="wrapper-dropdown-3" tabindex="1">

js

$(function () {

    var dd1 = new DropDown($('#dd1'));
    var dd = new DropDown($('#dd'));

    $(document).click(function () {
        // all dropdowns
        $('.wrapper-dropdown-3').removeClass('active');
    });

});