什么函数在$(document).ready() [英] when has a function to be in $(document).ready()

查看:93
本文介绍了什么函数在$(document).ready()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just don't get it. I searched and searched but for this I just can't figure out what's "right".

有三个例子。

1)小提琴1.0
我们这里有 html onlick =function javascript 功能正确那里工作正常

1) Fiddle 1.0 Here we have html with onlick="function" and the javascript function right there as well which works fine

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

2)小提琴2.0
然后当我将函数移动到脚本部分时(将其移动到.js文件)我得到一个错误ReferenceError:someFunction未定义

2) Fiddle 2.0 Then when I move the function to the script section (kind of move it to the .js file) I get an error "ReferenceError: someFunction is not defined"

这就是问题开始的地方

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

3) Fiddle 3 So now I have a function in document ready calling with .on(click which always works fine. This function is calling another function which is outside the docuemnt.ready() and also works fine.

所以问题。我什么时候必须定义函数哪里和为什么它总是有效?

So the question. When do I have to define the functions where AND WHY so it always works?

谢谢!

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

All the code from Example 3) looks like this:

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


推荐答案

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

A lot of what you're seeing is because of jsFiddle's very surprising default setting, which is to wrap the code in the script pane in an onload handler. So your code is wrapped in a function and no longer at global scope (which is where functions need to be if you use onclick-style attributes). You can change this with the drop-down box on the left (the second one, under the list of libraries and scripts). Change it to "no wrap" to have unwrapped code.

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

You're not (by far!) the first to be bit by this surprising default.

回答你的主要问题:


有一个函数在$(document).ready()

when has a function to be in $(document).ready()

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

If you control where the script tags loading your script go, you basically never have to use ready; instead, just make sure your script tags are at the end of the HTML, just before the closing </body>.

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

You can use ready, of course. The reason for doing so is to make sure that all the DOM elements have been created before your code runs. But if you put your script tag at the end, that's already true. You can still define your functions outside of the ready handler (if you want them to be globals), but if you're using ready, you would call them from the ready handler so the elements exist.

FWIW,我会避免使用 onclick -style属性来挂钩事件处理程序,主要是因为它们需要你创建全球职能。当我可以避免时,我宁愿避免创建任何全局符号。

FWIW, I would avoid using onclick-style attributes for hooking up event handlers, primarily because they require you to create global functions. I prefer to avoid creating any global symbols when I can avoid it.

我推荐的一般表格:

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

您的脚本如下所示:

(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

以下是一个完整的示例:实时复制

Here's a complete example: 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>

这篇关于什么函数在$(document).ready()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆