如何为多个项目使用我自己创建的jQuery函数?

时间:2012-11-22 21:24:23

标签: javascript jquery

请帮我把我的功能添加到所有div。我想用'每个',但不知道如何。

我需要2个警告信息,但是当我尝试使用$('div')。test()函数时,我只能成为第一个div。随着它仍然有效。

<html>
    <head>

        <style type="text/css">
            div {
                width:100px;
                height:100px;
                background: yellow;
                float: left;
                margin: 20px;
            }
        </style>

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    </head>

    <body>

        <div id="a"></div>
        <div id="b"></div>

        <script type="text/javascript">

            (function( $ ){

                $.fn.test = function() {

                    alert(this.attr('id'));

                };

            })( jQuery );

            //work
            $('#a').test();

            // not work
            //$('div').test();

        </script>
    </body>
</html>

感谢名单!

4 个答案:

答案 0 :(得分:3)

将提醒行更改为:

return this.each(function(){ alert(this.id); });

请参阅jQuery each的文档。

这是JSFiddle

答案 1 :(得分:2)

http://jsfiddle.net/bu952/1/

(function( $ ){

  $.fn.test = function() {

    return this.each(function() {
      alert(this.id);
    });

  };
})( jQuery );


$('div').test();

答案 2 :(得分:1)

你的第一个例子......

$('#a').test();

...有效,因为只有一个id为“a”的元素。但是,你的第二个例子......

$("div").test();

...不是因为它正在选择页面上

所有的div。

你需要这样的东西来支持这两种可能性:

(function($){
    $.fn.test = function() {
        // this is now all selected elements.
        // Loop through each selected element.
        $(this).each(function() {
            // this is now the element being looped.
            alert($(this).attr('id'));
        });
    };
})(jQuery);

jsFiddle:http://jsfiddle.net/2Ejux/

答案 3 :(得分:0)

你得到的答案适合你的情况。 如果您前往创作插件,我建议您阅读这些。使用任何插件模式都可以防止您发布问题。

http://docs.jquery.com/Plugins/Authoring - 它有一些提示和插件的基本结构

http://stefangabos.ro/jquery/jquery-plugin-boilerplate-oop/ - 全能插件结构

http://stefangabos.ro/jquery/jquery-plugin-boilerplate-revisited/ - 上述

的旧版本