我有以下功能:
$(document).ready(function(){
function fav(type){
switch(type){
case "radius":if(radius_fav.indexOf(rad)== -1){
radius_fav.push(rad);
}
break;
case "transform":if(transform_fav.indexOf(final_transformation) == -1){transform_fav.push(final_transformation);}
break;
default:if(bshadow !== none && box_fav.indexOf(bshadow) == -1){box_fav.push(bshadow);}
break;
}
}//end of switch statement
});
在 $(document).ready() 内部。除非将其放在 document.ready() 外部,否则此函数将无法工作。有什么想法吗?包含 html 页面中的 Jquery 标签 安慰: Uncaught ReferenceError :fav 未定义
最佳答案
I have the following function...Inside $(document).ready().This function won't work unless it is put outside document.ready().Any ideas?
听起来您正在从 onXyz
调用该函数属性,如下所示:
<div onclick="fav('radius')">...</div>
以这种方式调用的函数必须是全局,但是当您在 ready
中声明该函数时回调,它不是全局的,它的范围是 ready
回调。
最好避免创建全局变量,这是不使用 onXyz
的原因之一事件连接的属性。相反:
<div id="radius">...</div>
...然后在 ready
:
$("#radius").on("click", function() {
fav('radius');
});
...或类似的。
您不必提供所有这些 id
s,事实上,您很可能能够对其中的几个使用相同的处理程序。例如:
<div class="control" data-type="radius">...</div>
<div class="control" data-type="transform">...</div>
<!-- ... -->
然后
$(".control").on("click", function() {
fav(this.getAttribute("data-type"));
// Or:
// fav($(this).attr("data-type"));
// But not .data(), that's for something else, not for just accessing data-* attributes
});
<小时/>
请注意,您不需要 ready
在大多数情况下都可以发挥作用。只需将内联调用的函数表达式放在文档末尾,就在结束 </body>
之前标签:
<script>
(function() {
$(".control").on("click", function() {
fav(this.getAttribute("data-type"));
// Or:
// fav($(this).attr("data-type"));
// But not .data(), that's for something else, not for just accessing data-* attributes
});
})();
</script>
</body>
</html>
你真的只需要一个 ready
如果您不控制 script
的位置,则处理程序标签去。
关于javascript - document.ready 中的函数将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28926272/