无法设置未定义的属性'url'

问题描述 投票:2回答:4

在下面的示例中,我创建了typeahead类的实例

    var ta = $.typeahead({
        input: '.super',
        minLength: 0,
        maxItem: 15,
        order: "asc",
        hint: true,
        href: "",
        searchOnFocus: true,
        display: ["name"],
        template: "{{name}}",
        source: {
            "SearchResults": {
                //ajax: {
                //    url: "/search/" + id,
                //    path: ""
                //}
            }
        },
        callback: {
            onClickAfter: function (node, a, item, event) {
                event.preventDefault;
                debugger;
            }
        },
        debug: true
    });

稍后,并使用通过以下方法获得的id变量

    $("input").focus(function () { 
        id = $(this).attr("id");
        ta.source.ajax.url = "/search/" + id;
    }); 

i得到Cannot set property 'url' of undefined,因为ta.source.ajax实际上为空。我该如何解决?

简单地说,我不想为表单的每个输入创建重复的代码

jquery typeahead.js
4个回答
1
投票

通过Typeahead实例的SearchResults配置options property组。

options属性是从source生成的。

options


0
投票
我认为您应该使用ta.options.source.SearchResults.ajax.url = "/search/" + id; 而不是@freedomn建议的ta.source.SearchResults.ajax.url

ta.source.ajax.url

[另外,@ OrElse关于您的错误,请尝试将属性留空,不要将其注释掉。另外,尝试从SearchResults中删除双引号-

$("input").focus(function () { id = $(this).attr("id"); ta.source.SearchResults.ajax.url = "/search/" + id; });


0
投票
也许您正在使用某种jQuery库。但如果正确加载并初始化变量。而您获得了所有其他财产,那么这是一个小问题。让我们讨论一个可能的情况并了解问题

source: { SearchResults: { ajax: { url: "/search/" + id, path: "" } } },

当您将任何内容分配给“ ta”变量时,您可能会获得所有属性。但您收到错误消息“无法设置未定义的属性'URL'”。因此,您明确尝试使用的属性是URL。从逻辑上讲,它应该是ajax属性,但ajax本身未在您的变量中定义。因此,您应该首先定义ajax。

var ta = $.typeahead({ input: '.super', minLength: 0, maxItem: 15, order: "asc", hint: true, href: "", searchOnFocus: true, display: ["name"], template: "{{name}}", source: { "SearchResults": { //ajax: { // url: "/search/" + id, // path: "" //} } }, callback: { onClickAfter: function (node, a, item, event) { event.preventDefault; debugger; } }, debug: true });

始终确保事先定义了JSON变量,以后可以定义属性。

例如

var ta = $.typeahead({ input: '.super', minLength: 0, maxItem: 15, order: "asc", hint: true, href: "", searchOnFocus: true, display: ["name"], template: "{{name}}", source: { "SearchResults": { ajax: { // now ajax is defined and you will not get any error. } } }, callback: { onClickAfter: function (node, a, item, event) { event.preventDefault; debugger; } }, debug: true });

但是如果您使用类似下面的内容。

var a={} a.b.c=10 console.log(a.b.c)// you will get same error.

希望这会对您有所帮助。

0
投票
仅将行包装在if语句中以检查a.b={} a.b.c=10 console.log(a.b.c)// you will not get an error. 是否存在以防止其引发null错误的属性,该怎么办?>

ta.source.ajax

© www.soinside.com 2019 - 2024. All rights reserved.