0

请帮我将我的功能添加到所有 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

4 回答 4

3

Change your alert line to:

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

See the docs for jQuery each.

Here is a JSFiddle.

于 2012-11-22T21:30:22.000 回答
2

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

(function( $ ){

  $.fn.test = function() {

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

  };
})( jQuery );


$('div').test();
于 2012-11-22T21:31:14.223 回答
1

Your first example...

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

... works because there is only one element with the id of "a". However, your second example...

$("div").test();

... doesn't because it is selecting all of the divs on the page.

You will need something like this to support both possibilities:

(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/

于 2012-11-22T21:30:44.860 回答
0

你得到的答案对你的案子有用。如果您打算编写插件,我建议您阅读这些。使用任何插件模式都会阻止您发布问题。

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

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

http://stefangabos.ro/jquery/jquery-plugin-boilerplate-revisited/ - 上面的旧版本

于 2012-11-22T21:47:29.007 回答