0

我使用这个 javascript 通过扩展DropDown函数功能在类名上产生“切换”一个额外的单词,并在单击时将其删除:

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();*/
            return false;
        });
    }
}

$(function () {

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

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

});

我希望 JavaScript 在其中生效的 HTML 看起来像,(我的目标是 class="wrapper-dropdown"):

 <div class="wrapper">
     <div id='dd' class="wrapper-dropdown">1'st subject
         <ul class="dropdown">
             <li><a href="content.php?page=1">1</a></li>
             <li><a href="content.php?page=7">2</a></li>
             <li><a href="content.php?page=8">3</a></li>
         </ul>
     </div>
     <div id='dd' class="wrapper-dropdown">2'nd subject
         <ul class="dropdown">
             <li><a href="content.php?page=2">1</a></li>
             <li><a href="content.php?page=3">2</a></li>
         </ul>
     </div>
     <div id='dd' class="wrapper-dropdown">3'rd subject
         <ul class="dropdown"></ul>
     </div>
     <div id='dd' class="wrapper-dropdown">4'th subject
         <ul class="dropdown">
             <li><a href="content.php?page=9">1</a></li>
             <li><a href="content.php?page=11">2</a></li>
         </ul>
     </div> 
</div>

问题是 JavaScript 仅对包装器 div 中的第一项生效

4

1 回答 1

1

因为您有多个 div 且id='dd'- ID 必须是唯一的。

只需像这样向您的 div 添加一个dd类:

 <div class="wrapper-dropdown dd">1'st subject
     <ul class="dropdown">
         <li><a href="content.php?page=1">1</a></li>
         <li><a href="content.php?page=7">2</a></li>
         <li><a href="content.php?page=8">3</a></li>
     </ul>
 </div>

并更改elvar dd = new DropDown($('.dd'));

于 2013-02-06T09:22:18.357 回答