创建没有选择器先决条件的自定义jQuery函数 [英] Creating custom jQuery function without selector prerequisite
问题描述
我知道我可以使用$.fn.myFunction
构造函数来创建自定义jQuery插件,并将JavaScript中的自定义函数调用为$('selector').myFunction()
.
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').myFunction()
.
但是,对于我当前正在处理的项目,我需要能够定义一个不需要选择器即可工作的函数.这实际上是针对MessageBox插件的,其作用方式与C#相似MessageBox
类.因此,理想情况下,我想将函数创建为MessageBox
,然后按以下方式调用它:
However, for a project I'm currently working on, I need to be able to define a function that does not require a selector to work.This is actually for a MessageBox plugin, which will act in a similar manner to C#'s MessageBox
class. As such, I would ideally like to create the function as MessageBox
, and then call it as follows:
var myMessage = $.MessageBox();
,然后依次是myMessage.Show();
请注意,函数调用开始时jQuery引用中没有选择器限制.
Notice the lack of selector brakets in the jQuery reference at the beginning of the function call.
我们将很高兴收到关于最佳实践的任何建议.
Any advice on the best practice for this would be gratefully received.
推荐答案
这应该有效:
jQuery.MessageBox = function() {
var show = function() {
// something...
}
var hide = function() {
// something...
}
return {
show: show,
hide: hide
}
}
这篇关于创建没有选择器先决条件的自定义jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!