jQuery使用typeahead updater参数抛出typeError

时间:2013-01-01 00:48:08

标签: javascript jquery google-chrome twitter-bootstrap bootstrap-typeahead

如果您在http://djdavid98.zymichost.com/.tagguide/使用Google Chrome访问我的网站,并尝试使用搜索框(例如,键入' 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');
        ...
    },
});

2 个答案:

答案 0 :(得分:1)

它实际上在缩小的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控制台在查找错误时有时会“丢失”它的位置;他们很快就会被发现在同一个地方。您只需手动刷新路径即可将其重置。

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

答案 1 :(得分:0)

调用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) < / p>

进一步阅读该代码我相信$(this)返回undefined的原因是因为它在此代码中的.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;
    },
});

看 - 你在$('#findpony')之后调用#(this)。attr('placeholder')。attr('title')