Jquery形式的方法调用

<!DOCTYPE html>
<html>
<head> 
    <meta charset="utf-8">
    <title>jquery形式的方法调用</title>
    <script type="text/javascript" src="jquery.js"></script>
</head> 
<body>
    <div id="my">huangbaokang</div>
<script type="text/javascript">

    $.fn.extend({
        hbk:function(){
            console.log("hello world");
        }
    });

    $("#my").hbk();
</script>

</body>
</html>

自己定义了一个hbk方法,在Jquery对象元素上执行,可以看见控制台打印了hello world.

如果想支持Jquery的链式调用,如执行$(“#my”).hbk().css(‘backgroundColor’,’blue’);
则控制台报如下错误:
这里写图片描述
只需要在hbk方法中return this即可。

$.fn.extend({
        hbk:function(){
            console.log("hello world");
            return this;
        }
    });

猜你喜欢

转载自blog.csdn.net/huangbaokang/article/details/82118562
今日推荐