jQuery addClass函数似乎运行,但实际上并没有填充类名

时间:2013-10-24 21:37:01

标签: jquery html css

我在这里遇到一个奇怪的问题。

我开发了一个包含多个动作的搜索框。重要的一点是,当用户点击按钮时它会打开(或者应该......)。

HTML:

<form method="get" id="searchform" action="">
    <input type="search" placeholder="Search" size="18" value="" name="s" id="s" />
    <input type="submit" value=""></input>
</form>

CSS:

#searchform {
    position: relative;
    min-width: 40px;
    height: 80px;
    float: right;
}
#searchform input[type="search"] {
    margin-right: 40px;
    height:80px;
    width:2px;
    background:rgba(245, 245, 240, 1);
    padding: 0;

    -webkit-transition:all .2s ease-in-out;
    -moz-transition:all .2s ease-in-out;
    -o-transition:all .2s ease-in-out;
    transition:all .2s ease-in-out;
}
#searchform input[type="submit"] {
    background: rgba(255, 255, 255, 1);
    position: absolute;
    right: 0;
    top: 0;
    width: 40px;
    height: 80px;
}
#searchform.open input[type="search"] {
    width: 180px;
    padding: 0 0 0 20px;
}
#searchform.open input[type="submit"] {
    background:rgba(200, 160, 0, 1);
}

JS:

$('#searchform input[type="submit"]').click(function () {
    $("#searchform").toggleClass('open');
});

$('#searchform input[type="submit"]').click(function () {
    if ($('#searchform').hasClass('open') && $.trim($('#searchform input[type="search"]').val()).length === 0) {
        event.preventDefault();
        $('#searchform').removeClass('open');
    }
});

$(document).bind('click', function () {
    $('#searchform').removeClass('open');
});

$('#searchform').bind('click', function (event) {
    event.stopPropagation();
});

这是一个小提琴:http://jsfiddle.net/5zB8f/1/


开放动作非常简单。一个jQuery脚本将class="open"添加到#searchform,但它只添加了类......代码似乎有效,所以我不知道为什么它会像这样。

如果您手动将该类添加到html并运行它,您将看到它应该转换为什么。

感谢任何帮助。如果有人可以告诉我如何优化jQuery脚本,那么奖励积分......我确信我已经写了超过必要的工作......


编辑:我现在有toggleClass,但它与addClass的行为相同......

1 个答案:

答案 0 :(得分:3)

这是你需要的吗?

http://jsfiddle.net/5zB8f/3/

$('#searchform input[type="submit"]').click(function () {
    $("#searchform").toggleClass('open');
    if ($('#searchform').hasClass('open') && $.trim($('#searchform input[type="search"]').val()).length === 0) {
        event.preventDefault();
    }
    if ($("#searchform").hasClass("open")) return false;
});


$(document).bind('click', function () {
    $('#searchform').removeClass('open');
});

$('#searchform').bind('click', function (event) {
    event.stopPropagation();
});