我将 JavaScript 封装在一个自调用函数中,以保持所有内容都包含在内。然而,我遇到了一个问题,即我的链接(动态构建的)在单击时返回错误“函数未定义”。让我包含我的相关代码:
(function(window, document, $) {
function buildChapterList() {
for(var i=0; i<Object.keys(theChapterCues).length; i++) {
chapterListHTML = "<li><a class='fun-blue' href='javascript:void(0)' onClick=\"skipToChapter('"+ i +"')\">"+ theChapterCues[i]["title"] +"</a></li>";
$(chapterListHTML).appendTo("ul#chapter-list");
$("body").bind("DOMNodeInserted", function() {
$(this).find('#chapter-list li').first().addClass("active");
});
}
}
function skipToChapter(theChapter) {
if (theChapter == 0) {
theVideo.currentTime=0;
} else {
var thisChapterStart = parseInt(cues[theChapter]["chapterStart"]+1);
theVideo.currentTime=thisChapterStart/frameRate;
}
}
}(this, this.document, this.jQuery));
单击生成的链接之一时,我收到以下错误:
Uncaught ReferenceError :skipToChapter 未定义
我在范围上遗漏了什么吗?这是一个具有约束力的问题吗?任何建议将不胜感激。谢谢!
最佳答案
skipToChapter
函数不在全局范围内,因此无法从内联点击处理程序中调用。相反,您应该在构建链接时以如下所示的不引人注目的方式分配点击处理程序。如果您像这样分配它,那么 skipToChapter
就在范围内,您不必将其设置为全局的,并且您无需使用不需要的内联事件处理程序。
function buildChapterList() {
for(var i=0; i<Object.keys(theChapterCues).length; i++) {
chapterListHTML = $("<li><a class='fun-blue' href='javascript:void(0)'>"+ theChapterCues[i]["title"] +"</a></li>");
(function(i){
chapterListHTML.find('a').click(skipToChapter.bind(this, i));
})(i);
chapterListHTML.appendTo("ul#chapter-list");
$("body").bind("DOMNodeInserted", function() {
$(this).find('#chapter-list li').first().addClass("active");
});
}
}
关于javascript - 具有动态绑定(bind)内容的自调用函数作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26301387/