今天在做项目的过程中,遇到一个问题。当前的需求是:点击li,跳转页面并传一个参数。我把页面的展示内容是通过html拼接起来的。
for (var i = 0; i < list.length; i++) {
if(JY.Object.notNull(list[i].photoUrl)){
html+="<li class='item' onclick='preview(\"" + list[i].courseId + "\")'>";
html+="<a target='_blank'>";
html+="<img src='"+getImgPath()+"/"+list[i].photoUrl+"'/>";
html+="<span class='video-icon'></span>";
html+="<div class='title xsConInfo_1'>"+list[i].courseName+"</div>";
html+="</a></li>";
}else{
html+="<li class='item' onclick='preview(\"" + list[i].courseId + "\")'>";
html+="<a target='_blank'>";
html+="<img src='./img/no-img.png' />";
html+="<span class='video-icon'></span>";
html+="<div class='title xsConInfo_1'>"+list[i].courseName+"</div>";
html+="</a></li>";
}
};
preview点击方法是这样写的:
function preview(courseId) {
if(sessionPerson!=null){
if(sessionPerson.personType=="4"){
window.open(getBasePath()+"/education_city/xian_resource/student/leasonDetail.html?flag=teacherPreview&courseId="+courseId);
}else{
window.open(getBasePath()+"/education_city/xian_resource/student/leasonDetail.html?flag=studentPreview&courseId="+courseId);
}
}else{
toLogin();
}
};
但是根本就不生效,并且报错了:
查看了一下:这个报错信息指的是HTML里写的调用js报错的情况,根本原因是未找到函数,所以考虑可以按如下的方式解决:
1、js里面的方法书写格式不对,html页面搜索不到该函数。
格式应该为:*** = function() { 执行事件 };而不是 function xx (){};
2、js方法里面本来就有错误,页面就找不到他,包括与之相关联的函数。比如要调用a函数,a里面包括b函数,b函数有错误,a就不能用了。
(1) 第一种方法,注意不要写成var xx = function(){},不要加var,就会成为全局的函数;
(2) 第二种方法,function xx(){};这种写法也可以,不过要保证在js文件里的最外层,成为全局函数。
preview = function preview(courseId) {
if(sessionPerson!=null){
if(sessionPerson.personType=="4"){
window.open(getBasePath()+"/education_city/xian_resource/student/leasonDetail.html?flag=teacherPreview&courseId="+courseId);
}else{
window.open(getBasePath()+"/education_city/xian_resource/student/leasonDetail.html?flag=studentPreview&courseId="+courseId);
}
}else{
toLogin();
}
};