jquery:自定义下拉列表的复杂情况?

时间:2011-08-11 17:06:28

标签: jquery select drop-down-menu

我正在尝试构建一个类似于自定义下拉列表的选择框,只要我点击页面的其余部分或另一个下拉列表,就会关闭它。就像你期望的那样。

我目前正在做的方法是给每个下拉列表一个id,这样我就可以将它存储在变量中并检查它是否是当前的。

我的HTML

<div class="select width210" id="sortby1">
   <ul>
       <li class="option darr" title="oDisplay">show all</li>
       <li class="option" title="all">show all</li>
       <li class="option" title="published">published only</li>
       <li class="option" title="unpublished">private only</li>
   </ul>
</div>

我的JS:

   var currentSelectDiv = null;
$('.select ul li.option').click(function(e) {
        //storing the id attribute
        currentSelectDiv = $(this).parents("div.select").attr("id");
        selectedOption = $(this).parents("div.select").find(".option:first");
        console.log($(this));

        $(this).siblings().show();//.removeClass('darr');
        //$(this).addClass('darr');
        selectedOption.text($(this).text()).attr("title",this.title);
    });

$('.select ul li.option:not(".darr")').click(function(e) {
       $(this).parents("div.select").find(".option:not('.darr')").hide();
    });

    $(document).click(function(e) {
        $('.select ul li.option').each(function() {
            // check IDs to make sure only closing other lis
            if( $(this).parents("div.select").attr("id") !=
               currentSelectDiv) {
                if ( !$(this).is(":hidden" ) ) {
                    $(this).not('.darr').hide();
                }
            }
        });
        currentSelectDiv = null;
    });

实际上这很好用。我只有两个大问题。 首先,我需要让这个没有id的工作。仅仅因为我在我的页面上使用此下拉列表重复出现动态元素,因此存在多个相同ID的实例。因此我的代码不再起作用了,id当然应该是唯一的。

第二件事:我不知道如何倾听选项的实际“选择”。所以想象一下我想要console.log()我点击的选项的标题。我只能听一个选项上的每次点击,但实际上选项只是每隔一次点击。

以下是示例:http://jsfiddle.net/wRjBY/所以现在它工作正常,因为两个元素都有不同的ID。

知道如何解决这两件事吗?

3 个答案:

答案 0 :(得分:1)

New Code

我......稍微改进了代码。这应该可以帮助你。

$('.select .option').click(function(e) {
    e.stopPropagation();
    $(".select .option:not('.darr')").hide();
    selectedOption = $(this).parents("div.select").find(".option:first");

    $(this).siblings().show();
    selectedOption.text($(this).text()).attr("title",this.title);
});

$('.select .option:not(".darr")').click(function(e) {
   $(this).parents("div.select").find(".option:not('.darr')").hide();
});

$(document).click(function(e) {
    $(".select .option:not('.darr')").hide();
});

答案 1 :(得分:0)

对于您的第一个问题,您是否考虑过使用HTML5 data attributes而不是ID:

data-yourAttributeName='idValue'

您可以在jQuery中使用它,方法如下:

currentSelectDiv = $(this).parents("div.select").attr("yourAttributeName");

对于您的第二个问题,处理处理选择,您可以尝试使用类似于以下的功能:

//Ignores top-level and only selects from the drop-down
$('.option').not(':first').click(function()
{
    //Do whatever you need to do here         
});

<强> Working Demo (for 2nd part)

答案 2 :(得分:0)

您可以为id添加一个索引(并使其统一为所有这些)

<div id="selector1"...>...</div>

虽然您必须跟踪您拥有的数量,并根据下一个可用数字动态分配ID。

您可以在选项中添加onclick事件

<li class="option" onclick="somethingSelected()"...>...</li>

在选择某事时抓住。

希望这有帮助!