jQuery收回使用会影响其他div标签

时间:2012-09-17 15:34:16

标签: jquery html css

我正在尝试使用jquery显示一个下拉框。它运作良好。当我们在打开列表后点击页面的任何其他位置时,我还实现了隐藏下拉列表的选项。我已经使用了以下jQuery。

$('div.selectBox').each(function(){
    $(this).children('span.selected').html($(this).children('div.selectOptions').children('span.selectOption:first').html());
    $(this).attr('value',$(this).children('div.selectOptions').children('span.selectOption:first').attr('value'));
    $(this).children('span.selected,span.selectArrow').click(function(){
        if($(this).parent().children('div.selectOptions').css('display') == 'none'){
            $(this).parent().children('div.selectOptions').css('display','block');
        }
        else
        {
            $(this).parent().children('div.selectOptions').css('display','none');
        }
    });
    $(document).unbind('click');
    $(document).click(function(event){
        if($(event.target).closest('div.selectBox').length == 0) {
             $('.selectOptions').hide();                
        }
    });
    $(this).find('span.selectOption').click(function(){
        $(this).parent().css('display','none');
        $(this).closest('div.selectBox').attr('value',$(this).attr('value'));
        $(this).parent().siblings('span.selected').html($(this).html());
    });
});

当我们点击网站的任何其他部分时,它会完全关闭或隐藏。但问题是其他一些<div>标记在执行此操作后变为隐藏或display:none;

请告诉我一个解决方案。你可以看到它完全影响了上面的网址。如果您需要任何其他信息,请与我们联系。

2 个答案:

答案 0 :(得分:3)

$(this).toggleClass('open').next().toggle();

这一行在各个地方分散在你的代码中似乎导致了这个问题。我不确定它原本打算完成什么。它可能需要修改或者只是根据其意图进行删除。

修改

在玩了jsFiddle后,我可以看到它的目的是切换嵌套的子元素,并且需要更改为$(this).toggleClass('open');才能正常工作

答案 1 :(得分:2)

jsFiddle

Updated 9/21/2012 to reflect some of the other uses including a second menu without having 2 open at once

长话短说,我不包括你所有的其他工作,但对于BASE功能你想要的只是以下内容:

$(function() {
    // This will ensure it closes when clicked anywhere not on the element or its children
    $(document).click(function(e) {
        $(".open").removeClass("open");
    });

// the simple task of adding class
$(".createNew, .username, .notes").click(function(e) {
    var $this = $(this);
    // This next line ensures not having 2 open at once
    $(".open").filter(function(i){ return $this[0] != $(this)[0]; }).removeClass("open");
    e.stopPropagation(); // this prevents it closing via document.click
    $this.toggleClass("open");
});
});

如果你想在dif类名的多个元素上使用:

$(function() {
    $(document).click(function(e) {
        $(".createNew, .username, .notes").removeClass("open");
    });

    // the simple task of adding class
    $(".createNew, .username, .notes").click(function(e) {
        e.stopPropagation(); // this prevents it closing via document.click
        $(this).toggleClass("open");
    });

    // the rest
    $(".textbox").css({width:'100px', height: '33px'})
        .focus(function(e) {
            $(this).animate({width: '200px', height: '33px'});
        })
        .blur(function(e) {
            $(this).animate({width: '100px', height: '33px'});
        });
});