Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在jquery中创建函数_Jquery - Fatal编程技术网

在jquery中创建函数

在jquery中创建函数,jquery,Jquery,我试图创建一个jquery函数,并在下面的代码中使用,但没有得到任何输出。请告诉我制作过程 <script type="text/javascript"> (function($){ $.fn.myplugin = function(){ alert(this.id); }; })(jQuery); $("#sample").myplugin(); </script> (函数($){ $

我试图创建一个jquery函数,并在下面的代码中使用,但没有得到任何输出。请告诉我制作过程

<script type="text/javascript">
    (function($){
        $.fn.myplugin = function(){
            alert(this.id);
        };
    })(jQuery);

    $("#sample").myplugin();
</script>

(函数($){
$.fn.myplugin=函数(){
警报(this.id);
};
})(jQuery);
$(“#示例”).myplugin();
在该上下文中,这是一个jQuery对象,而不是原始DOM元素。

尝试更改

        alert(this.id);

当您获得jQuery对象数组时。

尝试以下操作:

<script type="text/javascript">
$(document).ready(function(){
    $("#sample").myplugin(this.id);
});

function myplugin(id) {
    alert(id);
}
</script>

$(文档).ready(函数(){
$(“#sample”).myplugin(this.id);
});
函数myplugin(id){
警报(id);
}

您可以在此处看到工作代码-

请注意,在运行上述代码时,文档中需要有一个id为“sample”的元素。另外,
this
指向jQuery对象,因此为了获得元素id,您需要使用以下任一项:

alert( this[0].id );

第一种更可取,因为它更快。

试试这个:

<script type="text/javascript">
 $(document).ready(function(){
  myplugin($("#sample"));
 });

  function myplugin(obj){
  alert(obj.id);
  }
</script>

$(文档).ready(函数(){
myplugin($(“#示例”);
});
函数myplugin(obj){
警报(对象id);
}

那么代码应该是什么?我将如何实现jquery函数?文档中是否有id为“sample”的元素?这个
script
标记是否放在HTML下面?如果没有,则用
$(document).ready(函数(){///代码开始了})包装代码您在哪个浏览器中?jQuery加载到页面上了吗?实际上我无法计算@Kanishka给出的解决方案,所以这个答案是对他的解决方案的改进。只是想分享一下
alert( this[0].id );
alert( this.attr('id') );
<script type="text/javascript">
 $(document).ready(function(){
  myplugin($("#sample"));
 });

  function myplugin(obj){
  alert(obj.id);
  }
</script>