jQuery 切换搜索表单不会提交一次 event.preventdefault

jQuery Toggled search form will not submit once event.preventdefault

我的导航栏中有一个搜索表单,当用户单击搜索按钮时,它会切换打开和关闭,最初使用 e.preventDefault() 来阻止搜索按钮提交表单。不幸的是,此功能似乎根本无法提交表单。

我试过使用这个 jQuery 条件语句,在输入字段不为空的情况下提交表单:

var sInput = $('#s').val();

if (sInput == null || sInput == '') {

    $('#search-button').on('click', function(e) {

        e.preventDefault();
        $('#s').animate({width: 'toggle'}).focus();
    });
}else{

    $('#search-button').on('click', function(e) {

        return true;
    });
}

而且,我试过使用这个:

$('#search-button').on('click', function(e) {

    if ( ! $(this).data('clicked') ) {

        e.preventDefault();
        $('#s').animate({width: 'toggle'}).focus();
    }

    $(this).data('clicked', true);
});

搜索表单:

                    <div id="search-wrap" class="cf menu-item">

                        <form class="searchform cf" method="get" action="<?php echo home_url(); ?>/">

                            <input type="search" id="s" name="s" class="field right">

                            <div class="search-button-wrap left">

                                <input type="submit" id="search-button" value="">
                            </div><!-- End #search-button-wrap -->
                        </form><!-- End .searchform -->
                    </div><!-- End #search-field -->

表单的样式:

#main-nav .menu-item {
    display:  inline-block;
}

#s {
    width:            200px;
    border:           none;
    outline:          #FCFCFC;
    display:          none;
    position:         relative;
    border-bottom:    solid 1px #C29D52;
    background-color: #FCFCFC;
}

#s.field {
    font-size:      1.125em;
    text-align:     center;
    letter-spacing: 2px;
}

.searchform input {
    display: block;
}

#search-button {
    width:               20px;
    height:              20px;
    border:              none;
    cursor:              pointer;
    background-color:    #FCFCFC;
    background-image:    url(images/search.png);
    background-repeat:   no-repeat;
    background-position: center;
}

#search-wrap {
    vertical-align: middle;
}

我希望打开搜索表单,以便用户可以输入他们的搜索关键字,如果他们没有输入任何关键字则关闭,如果他们输入关键字则提交。我不明白为什么我当前的代码不能那样工作。

将您的输入更改为 type="button" 并向您的表单添加一个 ID。在 JavaScript 的其他部分,手动提交表单(即 $("#formId").submit())。我也会稍微改变一下你的逻辑......

$('#search-button').on('click', function(e) {
    var sInput = $('#s').val();
    if (sInput == null || sInput == '') {
        $('#s').animate({width: 'toggle'}).focus();
    }else{
        $('#formId').submit();
    }
});