jQuery fn命名空间

时间:2011-04-03 01:42:29

标签: jquery

我正在阅读有关jQuery $ .fn命名空间的内容,为了理解我正在阅读的内容,如果没有采用快捷方式,我想要一个完整命令的示例。 例如,

$('p').click(function() {
console.log('click');
});

这可以用某个地方的.fn重写吗?什么是详尽的语法?

jQuery('p',document).fn.click(function() {
window.console.log('click');
});

2 个答案:

答案 0 :(得分:5)

jQuery.fnjQuery.prototype的别名;它是标准的Javascript原型机制 实际的jQuery 对象(实例)没有fn属性。

您需要使用thiscall调用函数,使apply关键字成为您调用它们的对象。

例如:

jQuery.fn.click.call(jQuery('p',document), function() { ... })

答案 1 :(得分:4)

jQuery的fn有点像C#的扩展方法。例如,jQuery没有用于切换隐藏和显示元素的内置函数,但是,您可以使用fn自己构建一个。一个例子:

<head>
<script src="jquery-1.4.4.js"></script>


<script type="text/javascript">    
    $(function() {     
        var toggle = true;

        $("a").click(function() {        
            $("p.neat").showIt(toggle,"fast");    
            toggle = !toggle;
            return false;
        });

        $.fn.showIt = function(b,param) { 
            if (b) 
                $(this).hide(param);
            else     
                $(this).show(param);
        };


    });

    $("p.neat").hide();   
</script>

</head>

<body>

 <p class="neat" style="width: 200">
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
 </p>

 <a href="/">Yeah</a> 
</body>

来自:http://www.ienablemuch.com/2010/06/first-foray-to-jquery.html