我在 JavaScript 函数中嵌套了函数,我想在 html 代码的主函数 photoGallery() 中调用它,但没有成功。我哪里错了?
JavaScript:
function photoGallery1() {
kartinki = new Array('images/green_salad1.png', 'images/green_salad2.png', 'images/green_salad3.png');
index = 0;
function next() {
index++;
if ( index >= kartinki.length) index = 0;
document.getElementById('image2').src = kartinki[index];
}
function previous() {
index--;
if ( index < 0) index = kartinki.length -1;
document.getElementById('image2').src = kartinki[index];
}
function start() {
index = 0;
document.getElementById('image2').src = kartinki[index];
}
}
HTML 代码:
<!Doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>The right eating of employed people</title>
<link rel='stylesheet' media='screen and (max-width: 1000px)' href='css/narrow.css'/>
<link rel='stylesheet' media='screen and (min-width: 1001px) and (max-width: 1235px)' href='css/medium.css' />
<link rel='stylesheet' media='screen and (min-width: 1236px)' href='css/wide.css' />
<link rel="stylesheet" href="css/calendarview.css">
<script src="js/photogallery.js"></script>
<script src="js/prototype.js"></script>
<script src="js/calendarview.js"></script>
<script type="text/javascript">
window.onload = function() {
Calendar.setup({
parentElement : 'calendar'
})
window.onload = photoGallery1()
}
</script>
最佳答案
第一:
window.onload = photogallery1();
导致 window.onload
属性出现未定义
值。
正如 @mrbinky3000 所说,您需要在 onload
事件处理程序中调用 photogallery1()。
此外,您需要一个具有公共(public)方法的对象,以便可以从外部范围访问它,在这种情况下,您需要一个构造函数:
function Photogallery() {
// Don't forget the "var" directive to prevent these from being global
var kartinki = new Array('images/green_salad1.png', 'images/green_salad2.png', 'images/green_salad3.png');
var index = 0;
this.next = function () {
index++;
if ( index >= kartinki.length) index = 0;
document.getElementById('image2').src = kartinki[index];
}
this.previous = function () {
index--;
if ( index < 0) index = kartinki.length -1;
document.getElementById('image2').src = kartinki[index];
}
this.start = function () {
index = 0;
document.getElementById('image2').src = kartinki[index];
}
}
现在你的加载发生了一些变化:
var photoGallery = null;
window.onload = function () {
// the other stuff you had
photoGallery = new Photogallery();
}
不要忘记声明 photoGallery
变量以避免它成为 implicitly declared global variable .
现在用一些 HTML 来调用对象上的方法:
<button type="button" onclick="photoGallery.next()">Next</button>
<button type="button" onclick="photoGallery.previous()">Previous</button>
关于javascript - 如何将 JS 的 main 函数调用到我的 html 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37727378/