Creating custom jQuery function without selector prerequisite

后端 未结 3 1433
天涯浪人
天涯浪人 2020-12-30 06:00

I know that I can create custom jQuery plugins by using the $.fn.myFunction constructor, and the calling the custom function in JavaScript as $(\'selector

3条回答
  •  星月不相逢
    2020-12-30 06:26

    relipse has a good point - as you are cluttering the main namespace. A solution if you have more objects than just eg. MessageBox is to create your own namespace like this:

    jQuery.myLib = {
      MessageBox: function() {
        var show = function() {
          // something...
        }
        var hide = function() {
          // something...
        }
        return {
          show: show,
          hide: hide
        }
      }
    }
    

    That means you are only taking one place in the main namespace (the name of your library, in this case myLib). You'd call it like this:

    jQuery.myLib.MessageBox.show()
    

提交回复
热议问题