0

I am trying to make this small plugin work but I am stuck at the moment. This is my first attempt to convert a function to a plugin.. Currently it's not working..

jQuery.fn.overlay_AS = function(opts) {

            clickable_link.click(function(evt){
                evt.preventDefault();

                var overlay_content = $('#'+current_link);

                overlay.children().fadeOut(200).promise().done(function () {
                    overlay_content.fadeIn();
                });
                //don't need to make the overlay fadeIn every time
                if (!overlay.is(':visible')) overlay.fadeIn(); 
            });

            overlay.click(function(){
                overlay.fadeOut();
                overlay.children().fadeOut(500);
            });         

        };

        $('.p_wrapper p').click(function(){
            $('.p_wrapper p').overlay_AS({
                clickable_link:$(this), 
                current_link:$(this).attr('class'),
                overlay: $('#overlay')
            });
        });

HTML:

<div class="p_wrapper">

    <p class="one">Link 1</p>

    <p class="two">Link 2</p>

    <p class="three">Link 3</p>

</div>

<div id="overlay">

    <p id="one">You clicked on p1</p>

    <p id="two">You clicked on p2</p>

    <p id="three">You clicked on p3</p>

</div>

ALl it does is fading an overlay in and loading different content depending on what link you clicked on.

4

2 回答 2

2

看起来您仍在尝试将插件视为普通函数,而不是作用于所选元素的函数。

将插件代码更改为此(我认为)您想要的,并且只需要您传入您希望使用的覆盖,因为您已经为链接选择了容器:

jQuery.fn.overlay_AS = function(overlay) {   
    // hide overlay and bind event to fadeout overlays when clicked
    overlay.children().hide();
    overlay.click(function(){
        overlay.children().fadeOut(500);
    }); 

    // return $(this) to enable chaining
    return $(this).each(function() {   // loop so plugin can be applied to multiple elements
        $(this).find('p').click(function(evt){ // bind click to each p tag
            evt.preventDefault();
            var overlayId = $(this).attr('class'); // get the overlay id
            var selectedOverlay = $('#' + overlayId); // select the overlay to show

            // hide overlays then show selected overlay
            overlay.children().fadeOut(500).promise().done(function () {
                selectedOverlay.fadeIn();
            });
        });
    });            
};

$('.p_wrapper').overlay_AS($('#overlay')); // Select the wrapper

JSFiddle 示例

我建议的另一个更改是使用data属性而不是类来选择覆盖:

HTML:

 <p data-overlay-id="one">Link 1</p>

JS:

 var overlayId = $(this).data('overlay-id);
于 2013-02-15T13:19:36.240 回答
0

除了理查德的回答之外,阅读它也可能会有所帮助:http ://docs.jquery.com/Plugins/Authoring#Getting_Started

于 2013-02-15T13:26:41.060 回答