在 jquery 中创建函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7470521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create function in jquery
提问by Dheeraj Agrawal
I am trying to make a jquery function, and used below code, but not getting any output. Please tell me the process to make it.
我正在尝试制作一个 jquery 函数,并在下面的代码中使用,但没有得到任何输出。请告诉我制作的过程。
<script type="text/javascript">
(function($){
$.fn.myplugin = function(){
alert(this.id);
};
})(jQuery);
$("#sample").myplugin();
</script>
回答by Misha Reyzlin
You can see the working code here – http://jsfiddle.net/gryzzly/YxnEQ/
你可以在这里看到工作代码 - http://jsfiddle.net/gryzzly/YxnEQ/
Note that you need an element with id "sample" to be present in your document when you are running the above code. Also, the this
is pointing at jQuery object, so in order to get the elements id, you need to use either of the following:
请注意,当您运行上述代码时,您的文档中需要一个 ID 为“sample”的元素。此外,this
指向 jQuery 对象,因此为了获取元素 id,您需要使用以下任一方法:
alert( this[0].id );
or
或者
alert( this.attr('id') );
The first is preferable, because it's faster.
第一个更可取,因为它更快。
回答by ip_x
Try this:
尝试这个:
<script type="text/javascript">
$(document).ready(function(){
myplugin($("#sample"));
});
function myplugin(obj){
alert(obj.id);
}
</script>
回答by Kanishka Panamaldeniya
Try this:
尝试这个:
<script type="text/javascript">
$(document).ready(function(){
$("#sample").myplugin(this.id);
});
function myplugin(id) {
alert(id);
}
</script>
回答by Dogbert
Try changing
尝试改变
alert(this.id);
to
到
alert(this[0].id);
As you're getting a jQuery object array.
当你得到一个 jQuery 对象数组时。
回答by Mike Thomsen
alert(this.attr('id'));
this
in that context is a jQuery object, not a raw DOM element.
this
在那个上下文中是一个 jQuery 对象,而不是一个原始的 DOM 元素。