[英]jquery very simple plugin, very basic
can we call jquery plugin like this? 我们可以这样称呼jQuery插件吗? this is in my plugin file
这在我的插件文件中
(function($) {
$.fn.alertme=function(){
alert('just testing');
};
}(jQuery));
i have included the plugin file ,, and calling the function on my home page... 我已经包含了插件文件,并在我的主页上调用了该函数...
<script>
$(document).ready( function() {
alertme();
});
</script>
I see an error message on console log Uncaught ReferenceError: alertme is not defined
i even tried return alert('just testing');
我在控制台日志上看到一条错误消息
Uncaught ReferenceError: alertme is not defined
我什至尝试return alert('just testing');
,, how do we fix this? ,我们该如何解决?
You added the function to $.fn
, which is an alias to the prototype of the jQuery constructor. 您将函数添加到
$.fn
,这是jQuery构造函数原型的别名。 That means your function is attached to all objects created as $(someArgs)
. 这意味着您的函数将附加到所有创建为
$(someArgs)
对象上。
Call your function on a jQuery object, for example 例如,在jQuery对象上调用函数
$(document).ready( function() {
$(document).alertme();
});
or 要么
$(document).ready( function() {
$({}).alertme();
});
or even 甚至
$(document).ready( function() {
$().alertme();
});
But there's no point in making a jQuery plugin if you don't use this
(the jQuery object) in the function. 但是,如果您不在函数中使用
this
插件(jQuery对象),那么制作jQuery插件毫无意义。 Usually you'd do something like this : 通常你会做这样的事情:
// logs all elements of the jQuery collection
$.fn.logme=function(){
this.each(function(){
console.log(this);
})
};
$(document).ready( function() {
$('p').logme();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.