繁体   English   中英

Javascript窗口[“ functionName”](参数)返回“不是函数” TypeError

[英]Javascript window[“functionName”](arguments) returns “is not a function” TypeError

我试图根据我的应用程序当前处于活动状态的选项卡运行AJAX函数。 当我在某些事件后调用该函数时,一切正常,但是我无法使用字符串变量动态地调用该函数。

按照以下答案: https : //stackoverflow.com/a/359910/5950111我刚刚收到一个TypeError,描述对象Im调用不是函数。

这是我的ajax函数:

function home_tab_fetchMore(items_count) {
    let request = new XMLHttpRequest();
    let output = []
    request.open('GET', `feedstream/${items_count}`);
    request.onload = function () {
        if (request.status === 200 && request.responseText != '') {
            let new_items = JSON.parse(request.responseText);
            for (let i = 0; i < new_items.length; i++) {
                let item = new_items[i];
                let event_id = feed_stream_row.children.length + 1;
                let feed_item = htmlToElement(`
                        <div class="grid-item" id="eventcard_${event_id}">
                        <div class="card-header">Featured</div>
                        <div class="card-body">
                        <h5 class="card-title">${item.fields['title']}</h5>
                        <p class="card-text">${item.fields['appointment']}
                        <br>
                        ${dummy_text.sentence(5, 40)}
                        </p>
                        </div>
                        </div>
                    `);
                // appending new item to DOM and updating masonry laytout
                feed_stream_row.appendChild(feed_item);
                msnry.appended(feed_item);
                output.push(feed_item);
            }
        } else {
            console.log('no response!');
        }
    };
    request.send();
    return output;
};

这是呼叫者事件:

$(window).scroll(function () {
    if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
        var fnstring = `${current_active_tab().id}_fetchMore`;
        var fn = window[fnstring]

        console.log(typeof(fnstring)) // returns: string type
        console.log(fnstring) // returns: home_tab_fetchMore without quotes
        console.log(fn) // returns: undefined

        fn(2) // returns: Uncaught TypeError: fn is not a function

        // however, this line works just as expected:
        home_tab_fetchMore(2)
    };
});

还有我无法理解的TypeError附加行:

Uncaught TypeError: fn is not a function
at main.js:128
at dispatch (jquery-3.3.1.slim.min.js:2)
at v.handle (jquery-3.3.1.slim.min.js:2)

感谢您提前提出的建议和指导,谢谢。

function home_tab_fetchMore(items_count) {}

除非调用此函数定义,否则在window对象中将无法使用以上函数定义。 而是使用函数表达式(在定义函数表达式之前不能使用它们)。

home_tab_fetchMore = function() {} OR
window.home_tab_fetchMore = function() {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM