[英]Create own JQuery Plugin
I want to create a very simple Jquery Plugin. 我想创建一个非常简单的Jquery插件。 What it does is return the parent of the element.
它所做的是返回元素的父级。 I searched and tried many different methods, still can't get it to run.
我搜索并尝试了许多不同的方法,但仍然无法运行它。
(function($){
$.fn.extend({
getParent:function(){
return this.each(function(){$(this).parent()});
}
});
})(JQuery);
in html 在HTML
<script type="text/javascript">
$(document).ready(function(e) {
alert($("#demos").getParent());
});
</script>
it should alert the parent of the $("#demos") 它应该提醒父母$(“#demos”)
You have typo here: 您在这里有错别字:
Replace JQuery
with jQuery
. 将
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>
You have a typo in your plugin. 您的插件中有错字。 It's
jQuery
, not JQuery
. 它是
jQuery
,而不是JQuery
。
(function($){
$.fn.extend({
getParent:function(){
return this.each(function(){$(this).parent()});
}
});
})(jQuery);
JQuery this.each()
returns just the items in this
. jQuery
this.each()
仅返回this
的项目。 So you will not get the parents by doing an each but only the selected item again. 因此,您将不会只通过一次选择而只获得每个项目,而不会得到父母。
If you would do just... 如果你愿意...
return $(this).parent();
...you would get what you want. ...你会得到你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.