我不知道为什么会发生这种情况,这可能只是一个基本错误,但我body
能够调用函数,因为:
Uncaught ReferenceError: changeImg is not defined
这是我相关的PHP/HTML:
<?php print("<body onLoad='javascript:changeImg(year_" . $p_date[0] . ")'>"); ?>
还有我的 JavaScript 函数:
var currentImg = 0;
var totalImg = 0;
var stored_year = 0;
$("#next-button").click(function() {
if (currentImg == totalImg) {
currentImg = 0;
}
else {
currentImg++;
}
changeImg();
});
$("#previous-button").click(function() {
if (currentImg == 0) {
currentImg = totalImg;
}
else {
currentImg--;
}
changeImg();
});
function changeImg(galleryYear) {
if (galleryYear = stored_year) {
$("#gallery-image").html("<img src='" + galleryYear.x_src[currentImg] + "'>");
$("#gallery-title").html(galleryYear.x_title[currentImg]);
$("#gallery-medium").html(galleryYear.x_medium[currentImg]);
$("#gallery-size").html(galleryYear.x_size[currentImg]);
$("#gallery-date").html(galleryYear.x_date[currentImg]);
var userCurrent = currentImg + 1;
var userTotal = galleryYear.x_id.length;
$("#current-post").html(userCurrent);
$("#post-total").html(userTotal);
var galWidth = $("#gallery-image" > "img").width();
$("#gallery").width(galWidth);
}
else {
currentImg = 0;
$("#gallery-image").html("<img src='" + galleryYear.x_src[currentImg] + "'>");
$("#gallery-title").html(galleryYear.x_title[currentImg]);
$("#gallery-medium").html(galleryYear.x_medium[currentImg]);
$("#gallery-size").html(galleryYear.x_size[currentImg]);
$("#gallery-date").html(galleryYear.x_date[currentImg]);
var userCurrent = currentImg + 1;
var userTotal = galleryYear.x_id.length;
$("#current-post").html(userCurrent);
$("#post-total").html(userTotal);
var galWidth = $("#gallery-image" > "img").width();
$("#gallery").width(galWidth);
$("#gallery-type").html('<img id="gallery-switch" alt="" src="images/gallery-icon.png" onClick="gallerySwitch()">');
stored_year = galleryYear;
}
}
它早些时候在工作,但为什么现在不呢?
当它说函数没有定义时,这通常意味着,声明函数的 javascript 必须在调用函数的代码之前调用。
在您的示例中(如果您粘贴整个代码会更好),我想您应该将 JS 代码放在 <head>
标签中,这应该可以解决您的问题。
另一种选择是使用 document.ready 事件或 document.load 事件,但不直接绑定在标记中,而是在正文的末尾。
我认为在您的代码中,year_" . $p_date[0] . "
是什么.
这可能是一个值。但是您已将其作为变量传递。
或者可能是函数更改Img未加载,或者在声明更改Img之前存在一些错误。
有时,如果 JavaScript 中存在一些错误或异常,则显示后的函数未定义。
问题似乎出在函数的主体上。 检查小提琴。http://jsfiddle.net/rajanrawat/3pCvX/
var currentImg = 0;
var totalImg = 0;
var stored_year = 0;
$("#next-button").click(function() {
if (currentImg == totalImg) {
currentImg = 0;
}
else {
currentImg++;
}
changeImg();
});
$("#previous-button").click(function() {
if (currentImg == 0) {
currentImg = totalImg;
}
else {
currentImg--;
}
changeImg();
});
function changeImg(galleryYear) {
alert('in here');
}
它获取函数。也许你没有在 ondom 准备好或里面绑定它
$(document).ready()