jQuery传递参数回调不工作.keyup()

时间:2016-07-17 15:50:39

标签: javascript jquery

我制作了一个简单的自动完成功能,如下所示:

Public Function RegExpReplace(ByVal varSource As Variant, _
        ByVal strPattern As String, _
        ByVal strReplace As String) As Variant

'version 2016-07-17

    Static re As Object
    Dim varOut As Variant

    If re Is Nothing Then
        Set re = CreateObject("VBScript.RegExp")
        re.Global = True
        re.IgnoreCase = False
    End If
    re.Pattern = strPattern
    varOut = Null
    If Not IsNull(varSource) Then
        varOut = re.Replace(varSource, strReplace)
    End If
    RegExpReplace = varOut
End Function

我正在尝试使用jQuery所描述的$(document).ready(function(){ $('#search-field').keyup(function(e) { ajaxAutocomplete(e); }); }); function ajaxAutocomplete(e) { var hash_tag = $.trim($(this).val()); $.ajax({ url : 'autocomplete.php', method : 'GET', dataType: 'html', data : {tag : hash_tag} }) .done(function(response) { if (response) { $('.datalistPlaceholder').html(response).show(); } else { $('.datalistPlaceholder').hide(); } }) .fail(function() { alert('Something went wrong'); }); } 函数中的事件对象:https://learn.jquery.com/about-jquery/how-jquery-works/

上述设置不起作用并返回:ajaxAutocomplete

从上面删除回调后,这确实有效:

jquery.js:7328 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

3 个答案:

答案 0 :(得分:1)

在结合Rory的上述答案并从MDN阅读.call()之后,我想出了以下有效的方法:

$(document).ready(function(){   
    $('#search-field').keyup(function(e) {
        ajaxAutocomplete.call(this, e);
    });
});

function ajaxAutocomplete(e) {
    console.log(e)
    var hash_tag = $.trim($(this).val());

    $.ajax({
        url     : 'autocomplete.php',
        method  : 'GET',
        dataType: 'html',
        data    : {tag : hash_tag}
    })
    .done(function(response) {
        if (response) {
            $('.datalistPlaceholder').html(response).show();
        } else {
            $('.datalistPlaceholder').hide();
        }
    })
    .fail(function() {
        alert('Something went wrong');
    });
}

键入' a':

的结果

j…y.Event {originalEvent: KeyboardEvent, type: "keyup", timeStamp: 1292.2500000000002, jQuery21406902543265129839: true, keyCode: 65…}

答案 1 :(得分:0)

您的第一个示例的问题是因为您在匿名函数中包含对ajaxAutocomplete()的调用,这意味着您在被调用函数中丢失了this的引用(它将指向{{ 1}}而不是window元素)。这反过来意味着#search-field没有返回任何内容 - 因此错误来自jQuery。

您需要在调用函数时使用$(this).val()来维护函数中.call(this)的范围:

this

Working example

或者你可以使用你的第二个方法将$(document).ready(function(){ $('#search-field').keyup(function(e) { ajaxAutocomplete.call(this); }); }); 函数引用传递给事件处理程序,然后保存范围:

ajaxAutocomplete

就个人而言,我更喜欢后一种方法。

答案 2 :(得分:0)

调用函数时,上下文this会丢失。如果直接使用回调,则可以使用上下文。