创建自己的JQuery插件

时间:2014-02-27 17:23:41

标签: javascript jquery

我想创建一个非常简单的Jquery插件。它的作用是返回元素的父元素。我搜索并尝试了许多不同的方法,仍然无法让它运行。

(function($){
$.fn.extend({
    getParent:function(){

        return this.each(function(){$(this).parent()}); 

    }


    });
})(JQuery);

in html

<script type="text/javascript">
    $(document).ready(function(e) {
alert($("#demos").getParent());
    });
</script>

它应该提醒$(“#demos”)

的父母

3 个答案:

答案 0 :(得分:2)

你有错字:

JQuery替换为jQuery

(function($){
$.fn.extend({
    getParent:function(){
        return this.each(function(){$(this).parent()}); 
    }
    });
})(jQuery);

$(document).ready(function() {
console.log($("#demos").getParent());
});

<div id="parent">
    <div id="demos"></div>
</div>

<强> DEMO

答案 1 :(得分:1)

你的插件中有拼写错误。它是jQuery,而不是JQuery

(function($){
$.fn.extend({
    getParent:function(){

        return this.each(function(){$(this).parent()}); 

    }


    });
})(jQuery);

答案 2 :(得分:0)

JQuery this.each()只返回this中的项目。因此,您不会通过执行每个父项而只是再次选择所选项目来获得父母。

如果你愿意......

 return $(this).parent();

......你会得到你想要的东西。