我有一个html文件,其中包含一个'onclick'事件,该事件调用一个也包含回调函数的javascript函数。我觉得我的语法有问题,因为我不能让回调函数执行。有人可以建议吗? 我在'open(x)'处获得了“非法调用”。
HTML:
<div id="div_friend"><img id="friend" class= "image_icon" src="images/friends_icon.png" onclick="friendReq('sections_panel', 'open');"></div>
的.js
function friendReq(x,callback){
var section_p = document.getElementById(x);
var option_p = document.getElementById('options_div');
var maxH = '300px';
var max_op = '200px';
//IF 'options_div' IS OPEN, CLOSE IT FIRST.
if(option_p.style.height == max_op){
option_p.style.height = '0px';
option_p.style.transition = 'height 0.8s'; <---code works up to here.
callback(x); // callback function to execute when above code has finnished.DOES NOT EXECUTE.
}else{ // This section works fine.
if(section_p.style.height == maxH){
section_p.style.height = '0px';
section_p.style.transition = 'height 0.8s';
}else{
section_p.style.height = maxH;
section_p.style.transition = 'height 0.8s';
}
}
}
function open(id){
var section_p = document.getElementById(id);
var maxH = '300px';
section_p.style.height=maxH;
section_p.style.transition = 'height 0.7s';
}
答案 0 :(得分:0)
首先,你有一个错字:
<div id="div_friend"><img id="friend" class= "image_icon" src="images/friends_icon.png" onclick="friendReq('sections_panel', 'open'"></div>
应该是:
<div id="div_friend"><img id="friend" class= "image_icon" src="images/friends_icon.png" onclick="friendReq('sections_panel', 'open');"></div>
第二,您将字符串传递给friendReq
函数,您将永远无法将字符串作为函数执行。您可以将参数名称更改为其他名称,因为在friendReq
函数中,open参数是您通过调用它获得的字符串。尝试删除该参数,因为它不需要作为回调传递,应该是:
function friendReq(x){
在此之后,我相信您的代码应正确调用open
函数
所以,从你的html开始,你正在调用friendReq('sections_panel', 'open');
,其中'open'实际上不是一个函数,也不是对open函数的引用,而是一个简单的字符串。现在,查看代码设计,您不需要将open函数作为回调参数传递,因为它们都在相同的范围内并且彼此看到。所以你可以这样做:
function friendReq(x){
var section_p = document.getElementById(x);
var option_p = document.getElementById('options_div');
var maxH = '300px';
var max_op = '200px';
//IF 'options_div' IS OPEN, CLOSE IT FIRST.
if(option_p.style.height == max_op){
option_p.style.height = '0px';
option_p.style.transition = 'height 0.8s'; <---code works up to here.
open(x); // callback function to execute when above code has finnished.DOES NOT EXECUTE.
}else{ // This section works fine.
//rest of your code
}
}
function open(id){
var section_p = document.getElementById(id);
var maxH = '300px';
section_p.style.height=maxH;
section_p.style.transition = 'height 0.7s';
}