gpt4 book ai didi

JavaScript 窗口 ["functionName"](参数) 返回 "is not a function"TypeError

转载 作者:行者123 更新时间:2023-12-01 01:29:08 25 4
gpt4 key购买 nike

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

遵循这个答案:https://stackoverflow.com/a/359910/5950111我刚刚收到一个 TypeError,描述我调用的对象不是一个函数。

这是我的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() {}

关于JavaScript 窗口 ["functionName"](参数) 返回 "is not a function"TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53458116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com