如果内容是活动的,在页面重新加载后取消选择jQuery中的文本框

Deselect a text box in jQuery after page reload if content is active

本文关键字:加载 取消 选择 文本 jQuery 新加载 活动 如果      更新时间:2023-09-26

我有一个Google即时样式jQuery搜索脚本,查询PHP文件,然后解析结果成HTMLdiv。当没有查询是活跃的文本框被自动选择,但当查询是活跃的,我希望它不被自动选择。我知道这可以通过使用.blur();函数来实现,但是当查询处于活动状态并且页面已经重新加载时,我如何才能使它仅使用.blur();函数呢?我希望大家都能理解我的问题。

我的jQuery代码是:
$(document).ready(function () {
    $('[id^=type_]').click(function () {
        type = this.id.replace('type_', '');
        $('[id^=type_]').removeClass('selected');
        $('#type_' + type).addClass('selected');
        return false;
    });
    $('#query').focus();
    if (window.location.hash != "") {
        var full = window.location.hash.replace('#', '');
        var queryType = full.substring(0, full.indexOf("/"));
        $('#type_' + queryType).click();
    } else {
        $('#type_search').click();
    }
    $('#query').keyup(function () {
        var query = $(this).val();
        var url = '/' + type + '/' + query + '/';
        window.location.hash = '' + type + '/' + query + '/';
        document.title = $(this).val() + ' - My Search Script';
        $('#results').show();
        if (query == '') {
            window.location.hash = '';
            document.title = 'My Search Script';
            $('#results').hide();
        }
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'html',
            success: function (results) {
                $('#results').html(results);
            }
        });
    });
    if (window.location.hash.indexOf('#' + type + '/') == 0) {
        query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
        $('#query').val(decodeURIComponent(query)).keyup();
    }
});

在审查了来源后,我发现我的怀疑是正确的。因为页面上只有一个文本框,一旦您模糊了查询框,它就会返回到它。你可以在你的html页面上设置另一个输入节点,例如

<input type="text" style="display:none" id="invisible">

,然后使用这个代码

if ($('#query').val().length) {
    $('#invisible').focus();
}

,这应该会让你到达那里:)

啊哈!我明白你的意思。您可以使用JQuery中的.val()函数检查文本框中是否有任何内容。假设"#query"是文本框,您可以将该部分更改为

if($('#query').val().length == 0)
$('#query').focus();