为什么我的ajax元素会立即失去焦点?

时间:2015-07-27 14:45:49

标签: javascript jquery ajax wordpress autocomplete

我尝试在Wordpress的标题字段中添加自动填充选项 - 我的某个自定义文档类型的标题通常(但并非总是)具有标准名称。

我已经迷上了Wordpress,添加了div suggestions title以下的onKeyUp,并添加了一个javascript val事件给标题告诉它根据到目前为止键入的内容向页面发出ajax请求。这一切都很好。

但是,目前我只能通过鼠标点击选择建议(然后使用#title来更新li的值。我也喜欢用户能够使用箭头键选择建议,谷歌。

我正在通过给出每个建议焦点来构建它(每一行都是tabindex元素,并且动态生成body。)

这适用于瞬间 - 期望的元素获得焦点 - 然后它立即失去它,返回<?php $sofar = stripslashes($_GET['sofar']); // This is important as otherwise the url gets confused and won't work on anything with an apostrophe in it. $common_file_names = array( "Here's suggestion 1", "This is suggestion 2", "Suggestion 3"); if(strlen($_GET['sofar'])>1) { //Ignores single letters echo '<ul id="autocomplete">'; $tabindex=0; foreach ($common_file_names as $suggestion) { if(false !== stripos($suggestion, $sofar)) : ?> <li tabindex="<?=$tabindex?>" onClick="acceptSuggestion('<?=addslashes($suggestion)?>')" onBlur="console.log('Lost focus!'); console.log(document.activeElement);"; ><?=$suggestion?></li> <?php $tabindex++; endif; } echo '</ul>'; } ?> 。为什么会这样?

gethint.php的代码:

$.ajaxSetup({ cache: false });

window.onload = function () {
    $( "<div id='suggestions'></div>" ).insertAfter( "#title" );

    $(document).on('keydown', '#title', function (){
          var hint_slash = this.value;
          showHint(hint_slash);
          checkKey(event);
    });



    $(document).on('focus', '#acf-field-extranet_client_area', function (){
         clearSuggestions();
    });
    $(document).on('focus', '#acf-field-extranet_document_type', function (){
         clearSuggestions();
    });
    $(document).on('focus', '#acf-date_picker', function (){
         clearSuggestions();
    });
    $(document).on('focus', '#acf-file-value', function (){
         clearSuggestions();
    });


    console.log("Scripts loaded successfully");
}

function showHint(str) { //If the user has typed 2 or more characters, this function looks for possible matches among common document names to speed up data entry.
    var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("suggestions").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "/gethint.php?sofar=" + str, true);
        xmlhttp.send();
}


function acceptSuggestion(str) {
    $('#title').val(str); //Puts the clicked suggestion into the title box.
    clearSuggestions();
}

function clearSuggestions() {
    showHint(""); //Clears suggestions.
}

function checkKey(event) {
    console.log('Key press: ' + event.keyCode);
    if(40 == event.keyCode) {
        event.preventDefault(); // Stops scrolling.
        var autocomplete =  $("#autocomplete");
        $(autocomplete.children('li:nth-child(' + 2 + ')')).focus() ;
        console.log(document.activeElement);
        }

    }

JS代码:

cursor.execute("DELETE FROM %s WHERE COL=%s" % ("tablename","column"))

这只是当前的测试代码,因此始终将焦点设置为第3个子元素。

2 个答案:

答案 0 :(得分:1)

我不会尝试专注于这些建议。在这种情况下,您必须将密钥检查代码添加到每个建议中,因为输入将失去焦点。相反,为&#34; focus&#34;创建一个CSS类。建议,删除键上/下键上的类,并将其添加到上一个/下一个建议...

 $input.keyup(function(e) {

    if(e.which == 38) {
        // up key
        var active = $('.suggestions li.active');
        if(active.length) {
            active.removeClass('active');
            active.prev().addClass('active');
        } else {
            $('.suggestions li:last').addClass('active');
        }
    } else if(e.which == 40) {
        // down key
        var active = $('.suggestions li.active');
        if(active.length) {
            active.removeClass('active');
            active.next().addClass('active');
        } else {
            $('.suggestions li:first').addClass('active');
        }

    }
});

答案 1 :(得分:0)

在@ evilunix的答案的基础上,我意识到每次击键都重置了#suggestions div,这意味着它永远不能保持焦点(或保留附加的类等)。

所以,编写了一个名为checkKey的新函数:

function checkKey(e) {  
    if(e.which == 38) {
        // up key
        e.preventDefault(); //Stops scrolling and cursor movement.
        var active = $('#suggestions li.active');
        if(active.length) {
            active.removeClass('active');
            active.prev().addClass('active');
        } else {
            $('#suggestions li:last').addClass('active');
        }
    } else if(e.which == 40) {
        // down key
        e.preventDefault(); //Stops scrolling and cursor movement.
        var active = $('#suggestions li.active');
        if(active.length) {
            active.removeClass('active');
            active.next().addClass('active');
        } else {
            $('#suggestions li:first').addClass('active');
        }
    } else if(e.which == 13) {
        //Return key
        e.preventDefault(); //Stops form submission.
        acceptSuggestion(document.getElementsByClassName('active')[0].innerHTML);
    } else {
        console.log(e.which);
        showHint($('#title').val());    
    }
}

并将#title onKeydown事件更改为:

$(document).on('keydown', '#title', function (){
        checkKey(event);
});

现在#suggestions仅在按键不是向上箭头,向下箭头或返回时刷新,并且在acceptSuggestion上有liactive类的返回运行时<input type="text" class="incident-message" name="message" id="message_@Model.IncidentId" value=""> <a href="/RegisterAjax/@Model.IncidentId" class="incident-link" id="send_@Model.IncidentId">Send a Comment</a>