【问题标题】:function inside document.ready won't workdocument.ready 中的函数不起作用
【发布时间】:2015-03-08 12:15:48
【问题描述】:

我有以下功能:

$(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 is not defined

【问题讨论】:

  • 那么为什么要把它放在伪就绪处理程序中呢?我猜你正面临范围问题,检查你的控制台是否有错误

标签: javascript jquery


【解决方案1】:

我有以下函数...在 $(document).ready() 中。除非将它放在 document.ready() 之外,否则此函数将不起作用。有什么想法吗?

听起来您是从 onXyz 属性调用函数,如下所示:

<div onclick="fav('radius')">...</div>

以这种方式调用的函数必须是globals,但是当您在ready 回调中声明该函数时,它不是全局的,它的作用域是ready 回调。

最好避免创建全局变量,这是不使用onXyz 属性进行事件连接的原因之一。而是:

<div id="radius">...</div>

...然后在ready:

$("#radius").on("click", function() {
    fav('radius');
});

...或类似的。

您不必将所有这些都提供给ids,事实上您可能可以对其中的几个使用相同的处理程序。例如:

<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 函数。只需将内联调用的函数表达式放在文档末尾,就在结束 &lt;/body&gt; 标记之前:

<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>

如果你不控制script 标签的去向,你真的只需要一个ready 处理程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    相关资源
    最近更新 更多