Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么赢了';我的自定义函数不能工作吗?_Javascript_Jquery_Html - Fatal编程技术网

Javascript 为什么赢了';我的自定义函数不能工作吗?

Javascript 为什么赢了';我的自定义函数不能工作吗?,javascript,jquery,html,Javascript,Jquery,Html,创建我自己的jQuery方法时,为什么这样做: (function($){ $.fn.test = function() { return this.each(function(){ $(this).html("Hi there"); }); } })(jQuery); $(document).ready(function(){ $("body").click(function(){ $(this)

创建我自己的jQuery方法时,为什么这样做:

(function($){
    $.fn.test = function() {
        return this.each(function(){
            $(this).html("Hi there");
        });
    } 
})(jQuery);
$(document).ready(function(){
    $("body").click(function(){
        $(this).test().css("color", "orange");
    });
});
但事实并非如此

(function($){
    $.fn.test = function() {
        return this.each(function(){
            $(this).html("Hi there");
        });
    } 
    $("body").click(function(){
        $(this).test().css("color", "orange");
    });
})(jQuery);
我尝试用
jQuery
替换
$
,但仍然不起作用。它似乎只在一个单独的doc.ready函数中工作,有人能解释为什么吗


谢谢

您的第二个代码段未按预期工作,因为

(function($) {...})(jQuery)
在文档准备就绪之前运行

通过包装你的

$('body').click(function () {...})

$(document).ready(function() {...})
您正在告诉jQuery运行

$('body').click(function () {...})
在页面加载之后


你(可能)想做什么:

$(document).ready(function() {
    $.fn.test = function() {
        return this.each(function() {
            $(this).html("Hi there");
        });
    }
    $("body").click(function() {
        $(this).test().css("color", "orange");
    });
});
这将运行两个

$.fn.test = function() {...}

$("body").click(function() {...}

文档准备好后(基本上是在页面完全加载时,这有点不同,但在这里阐述这一点并不具有建设性)。

因为第二个在文档准备好之前运行?这是否包含在标题中的脚本中?我想您会发现您的自定义函数确实可以工作,但是
“body”
选择器返回了一个空的jQuery对象,因为body还没有被解析。这个脚本在哪里运行?在
底部附近?