JavaScript Coffee 死活就是不起作用……

cassiuschen · January 07, 2014 · Last by cassiuschen replied at January 24, 2014 · 2528 hits

前端这一段用:

<div class="ui black huge launch right attached button" id="back_to_index" style="width: 70px;">
    <i class="icon list layout"></i>
    <span class="text" id="back_to_index_word" style="display: none;">返回首页</span>
</div>

然后依次引用了jQurey,jQurey.easing 在对应 controller 的 coffee 中写了:

$back = $("#back_to_index")
$backword = $("#back_to_index_word")
$(document).ready ->
    $back.mouseenter ->
        $back.animate( {'width':'175px'} , { duration:1000,easing:'jswing' })
        $backword.css("display","inline")
        return

    $back.mouseleave ->
        $back.animate( {'width':'70px'} , { duration:1000,easing:'easeInOutCirc' })
        $backword.css("display","none")
        return
    return

然后 mouseenter 和 mouseleave 死活就是不能激活……没高明白问题出在哪里了…………

为什么 $back$backword 放在 $(document).ready 外面?

#1 楼 @nightire 诶……!!居然就坑在这里了……什么情况这是…………传说中的闭包性?

#2 楼 @cassiuschen 查一下 document.ready 事件就知道了,基本等价于 window.load,更健壮一些。

It's not about closure. Of course you can access global variables within a function.

The problem is, if you load javascript in head by default, when the script executes $back = $("#back_to_index"), such dom elements is not loaded yet, so $back is null.

Putting it inside jquery ready will solve this issue because at that time the element does exist.

#5 楼 @billy Wow that's what exactly I wanna figue out! Thanks a lot!

You need to Sign in before reply, if you don't have an account, please Sign up first.