开发者

Jquery scope question

开发者 https://www.devze.com 2023-01-31 02:15 出处:网络
My first foray into writing jQuery functions. I have this function, but I\'m not sure why the overlay var has to be outside the scope of the click function.I tried it within but it doesn\'t work righ

My first foray into writing jQuery functions.

I have this function, but I'm not sure why the overlay var has to be outside the scope of the click function. I tried it within but it doesn't work right. Can I refactor this to make it better?

(function($) {
  $.fn.popOver = function() {

    // Variable for overlay
    var overlay = $("<div id='overlay'></div>");

    // Listen for clicks
    return this.click(function(e) {

      // Prevent the anchor link from loading
      e.preventDefault();

      // Variable for popover
      var popover = $(this).next();

      // Append the overlay to the document body
      $('body').append(overlay.click(function() {
        overlayHide();
      }))

      //Set the css and fade i开发者_JS百科n our overlay
      overlay.show();
      popover.fadeIn(150);

      // Listen for clicks on elements
      popover.find('a').click(function() {
        overlayHide();
      })

      // Hide Overlay function
      function overlayHide() {
        overlay.remove();
        popover.fadeOut(150);
      }

    })
  }
}) (jQuery);


Because you are not doing anything more specific than simply calling that other function, you can change lines like this...

popover.find('a').click(overlayHide);
0

精彩评论

暂无评论...
验证码 换一张
取 消