在做前端超链接onclick编程时,浏览器报错xx is not defined at HTMLAnchorElement.onclick,经过检查发现我把onclick函数写到了jquery的$().ready()中了,这样HTML页面搜索不到该函数,解决方法有两种,一种是将onclinck函数写在$().ready()之外、另一种是采用XXX=function (){}的匿名函数形式。下面为详细讲解一下。
错误代码示例
HTML:
<a onclick='showDetail()'>详情</a>
JS:
<script>
$().ready(function() {
function showDetail(){
console.log("detail");
}
});
</script>
方法1:将onclinck函数写在$().ready()之外。
<script>
$().ready(function() {
//......
});
function showDetail(){
console.log("detail");
}
</script>
方法2:采用XXX=function (){}形式
<script>
$().ready(function() {
//其他jquery代码
showDetail = function(){
console.log("detail");
}
});
showDetail();
</script>