jQuery使用typeahead updatater参数抛出typeError

jQuery throws a typeError using typeahead updater parameter

本文关键字:typeError 参数 updatater 使用 typeahead jQuery      更新时间:2023-09-26

如果您访问我的网站与谷歌浏览器在http://djdavid98.zymichost.com/.tagguide/,并尝试使用搜索框(例如:键入'a',单击第一个选项),您将在控制台中看到,jQuery记录了一个Uncaught TypeError: Cannot call method 'toLowerCase' of undefined。我不明白为什么。

问题一定在这部分代码中,因为删除它可以修复一切:

tagguide.js(第20-46行):
$('#findname').typeahead({
    ...
    updater : function (item) {
        $('#ponies li:contains('+$(this).val()+')').parent().parent().parent().addClass('in');
        ...
    },
});
$('#findpony').typeahead({
    ...
    updater : function(item){
        $('#'+$('div.accordion-group > div > a.accordion-toggle:contains('+$(this).val()+')').attr('id')).addClass('in');
        ...
    },
});

它实际上位于缩小后的jQuery文件中的一行,箭头指向它:

2148

val: function( value ) {
    var hooks, ret, isFunction,
        elem = this[0];
    if ( !arguments.length ) {
        if ( elem ) {
            hooks = jQuery.valHooks[ elem.type ] ||
                    jQuery.valHooks[ elem.nodeName.toLowerCase() ]; //<<<<<<<
                if ( hooks && "get" in hooks && 
                     (ret = hooks.get( elem, "value" )) !== undefined ) {
                return ret;
        }
        ret = elem.value;
        return typeof ret === "string" ?
            // handle most common string cases
            ret.replace(rreturn, "") :
            // handle cases where value is null/undef or number
            ret == null ? "" : ret;
    }
    return;
}​

2174

我注意到Chrome控制台有时会"失去"它的位置时,定位错误;他们很快就会在同一个地方被发现。你只需要手动刷新路径来重置它。

解决方案是双重的,将$(this).val()从回调参数中替换为item,这会抛出错误。

jquery调用未定义的.val()时抛出错误

就是这一行

$('#ponies li:contains('+$(this).val()+')').parent().parent().parent().addClass('in');

$('#ponies li:contains(a)').parent().parent().parent().addClass('in');

将模拟如果你只在文本框中输入"a"的值,如果这有效,那么你需要得到$('#findname')的。val()而不是$(this)

进一步阅读代码,我认为$(this)返回undefined的原因是因为它在代码中的2 .attr()之后被调用:

$('#findpony').attr('placeholder',function(){
    // code removed     
}).attr('title',function(){
            // code removed
}).typeahead({
    source  : ponylist,
    updater : function(item){ 
        $('#'+$('div.accordion-group > div > a.accordion-toggle:contains('+$(this).val()+')').attr('id')).addClass('in');
        return item;
    },
});
在$('# findony ').attr('placeholder').attr('title')之后调用#(this)