什么函数在$(document).ready()

car*_*mba 8 javascript jquery

我只是不明白.我搜索和搜索,但为此我只是无法弄清楚什么是"正确的".

有三个例子.

1)小提琴1.0 下面我们就htmlonlick="function"javascript功能权限有作为,工作正常

 <span class="classic one"   onclick="someFunction(this,'one')">CLICK HERE</span>

 <script type="text/javascript">
    function someFunction(obj,nr) {
        var string = $(obj).attr('class');
        $('.result').text( string );
    }
</script>
Run Code Online (Sandbox Code Playgroud)

2)小提琴2.0 然后当我将函数移动到脚本部分(将其移动到.js文件)时,我收到一个错误"ReferenceError:someFunction not defined"

这就是问题开始的地方

3)小提琴3 所以现在我有一个函数在文件就绪调用.on(点击它总是工作正常.这个函数调用另一个函数,在docuemnt.ready()之外,也工作正常.

所以问题.我何时必须定义函数where AND WHY以便它始终有效?

谢谢!

示例3)中的所有代码如下所示:

<div class="result">result</div>

    <span class="classic one"   onclick="someFunction(this,'one')">CLICK HERE</span>
    <span class="classic two"   onclick="someFunction(this,'two')">CLICK HERE</span>
    <span class="classic three" onclick="someFunction(this,'three')">CLICK HERE</span>
    <span class="classic four"  onclick="someFunction(this,'four')">CLICK HERE</span>

<div class="ready">ready</div>


<span class="callOtherFunction">Call other function</span>


<script type="text/javascript">
    $(document).ready(function(){
        $('.ready').text( 'dom is ready' );

        function someFunction(obj,nr) {
                var string = $(obj).attr('class');
                $('.result').text( string );
            }

         $( "span.callOtherFunction" ).on({
            click: function() {
                $(this).css("color","red");
                $(this).addClass("xyz");
                otherFunctionCallingFunction($(this));
            }
        });

    });

    function otherFunctionCallingFunction($me) {
        $('.callOtherFunction').append( ' --> ' + $me.attr('class') );
    }
</script>
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 15

您看到的很多内容是因为jsFiddle 非常令人惊讶的默认设置,即将代码包装在onload处理程序的脚本窗格中.所以你的代码被包装在一个函数中,而不再是全局范围(如果你使用onclick-style属性,那就是函数需要的地方).您可以使用左侧的下拉框(第二个,在库和脚本列表下)更改此设置.将其更改为"无包装"以包含未包装的代码.

你不是(到目前为止)第一个被这个令人惊讶的默认值所困扰的人.


回答你的主要问题:

什么函数在$(document).ready()

如果您控制script加载脚本的标记的位置,您基本上不必使用ready; 相反,只需确保您的script标签位于HTML 的末尾,就在结束之前</body>.

当然,你可以使用ready.这样做的原因是确保在代码运行之前已经创建了所有DOM元素.但如果你把你的script标签放在最后,那就已经是真的了.您仍然可以在ready处理程序之外定义函数(如果您希望它们是全局变量),但是如果您正在使用ready,则可以从处理程序中调用它们,ready以便元素存在.


FWIW,我会避免使用onclick-style属性来挂钩事件处理程序,主要是因为它们需要你创建全局函数.我宁愿避免在我可以避免的情况下创建任何全局符号.

我建议的一般形式:

<!-- ...your page markup here... -->
<script src="any_libraries_you_need_if_you_are_not_combining.js"></script>
<script src="your_script.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

你的脚本看起来像这样:

(function($) { // A scoping function that wraps everything
    // Hook up event handlers here. You can use `$` for jQuery, even if
    // you've used noConflict, because we have a private `$` symbol (see
    // the `$` argument above)

    // The body of your code goes here

})(jQuery); // <== Note how we're passing the jQuery reference in
            // and immediately executing the scoping function
Run Code Online (Sandbox Code Playgroud)

这是一个完整的例子:Live Copy

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Script Placement Example</title>
</head>
<body>
  <input type="button" class="hello-button" value="Click me">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
  <script>
    // This would be in a file, rather than inline
    (function($) {
      // Hook up handlers
      $(".hello-button").click(sayHello);

      // Body of the code
      function sayHello() {
        $("<p>Hello!</p>").appendTo(document.body);
      }
    })(jQuery);
  </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)