jQuery应该只用在ready事件处理程序中吗?

Ste*_*ten 1 javascript jquery

我已经读过使用jQuery在ready处理程序之外的代码,有什么缺点,如果有的话这样使用它?无论出于何种原因,我都对这种方式感到不舒服.

来自和ASP.NET MVC的内联脚本视图:

<script type="text/javascript">
    function foo() {
        if ($("#checkAll").attr("checked")) {
            $(".setColumns").attr("checked", true);
        }
        else {
            $(".setColumns").attr("checked", false);
        }

    }
</script>
Run Code Online (Sandbox Code Playgroud)

hex*_*ide 6

没有任何缺点.只是你需要等待DOM元素加载才能被操作.例如,如果你有这样的代码:

<script type="text/javascript">
  console.log($('#el').html());
</script>

<div id="el">Text</div>
Run Code Online (Sandbox Code Playgroud)

该函数不会返回值,因为div尚未加载.