<input type =“ text” lost =“” focus =“” after =“” 1'st =“” key =“” press =“” in =“” chrome =“”

时间:2019-05-09 18:59:27

标签: php jquery html

2 个答案:

答案 0 :(得分:1)

您的搜索输入失去焦点,因为新打开的窗口将获得焦点。

此外,使用您当前的代码,每次检测到长度超过两个字符的输入都会打开一个新窗口。

有很多解决方案,这里有两个。我没有将它们放入代码段中,因为它们无法正常工作。


AJAX

由于AJAX请求,您可以获得main.php生成的HTML:

HTML

<div class="search-container">
    <input type="text" placeholder="Search.." name="searchb" >
</div>

<div id="searchb-result"></div>

JavaScript

$('input[name="searchb"]').on('input propertychange paste', function() {
    // Empties the result container.
    $('#searchb-result').empty();

    if ($(this).val().length > 2) {
        document.cookie = `psearch=${this.value};path=/`;

        // Gets the HTML by AJAX and adds it to the result container.
        $.get('main.php', `psearch=${this.value}`, (html) => {
            $('#searchb-result').html(html);
        });
    }
});

<iframe>

您可以在<iframe>标签中加载URL。

HTML

<div class="search-container">
    <input type="text" placeholder="Search.." name="searchb" >
</div>

<iframe style="display:none;"></iframe>

JavaScript

$('input[name="searchb"]').on('input propertychange paste', function() {
    // Hides the <iframe> by default.
    $('iframe').hide();

    if ($(this).val().length > 2) {
        document.cookie = `psearch=${this.value};path=/`;

        // Updates the <iframe> source when an input is detected.
        $('iframe')
            .attr('src', `main.php?psearch=${this.value}`)
            .show();
    }
});

答案 1 :(得分:0)

我重写了整个部分,没有使用jquery,clean和4级方法,但是它可以工作。失去重点是问题。

<div class="search-container">
      <input type="text" placeholder="Search.." name="searchb" id="search" autofocus="autofocus">
</div>

<script>
window.name = 'parent';

search.onchange = search.oninput = search.onpaste = function() {
        var sv = search.value;
    if (sv.length > 3){
        var search_window = window.open("main.php?psearch="+sv, "iframe_a");
        parent.focus();
        }
    else {
        document.cookie = "psearch=";"path=/";
        var search_window = window.open("main.php?psearch=", "iframe_a");
        parent.focus();
    }

}
</script>