开发者

Operating on a string rather than a selector from a jQuery Plugin

开发者 https://www.devze.com 2023-04-05 11:21 出处:网络
I want to create a plugin that works like so: var fmatted = $(\'someString\').myFunction(); I\'ve developed jQuery functions in the following manner:

I want to create a plugin that works like so:

var fmatted = $('someString').myFunction();

I've developed jQuery functions in the following manner:

$(someSelector).someFunction();

I know that the selector gets converted to a jQuery object and can be used via this in the plugin. However, if I want to use a string rather than a selector, I'm not sure how I can access that string within my plug开发者_StackOverflowin.

Basically, I want to be able to use a plugin to operate on something other than a selector, very much like jQuery's .trim() function, but I can't figure out how to access that within the plugin.


jQuery(selector)[docs] (or $(selector)) is used to create a jQuery object containing elements that match the selector. Although it is possible for you to create a method which ignores the elements and retrieve the original selector, this is not efficient and makes it more difficult to understand what your code is doing.

jQuery.trim()[docs] is not implemented like that. In fact, notice that jQuery.trim() isn't a method on a jQuery object at all! If it were, you'd invoke it like this:

jQuery("   foo   ").trim();

Instead, you do this:

jQuery.trim("   fooo   ");

.trim() is a method, but not a method of jQuery objects. It's a method of the jQuery constructor function itself (in some languages you would call this a "class method").

You're not creating an object and the argument is never treated as a selector. To add a function like this yourself, all you need to do is this:

jQuery.someFunction = function(message) { alert(message); };

More idiomatically, the default behaviour of the jQuery.extend[docs] will do this for you:

jQuery.extend({someFunction: function(s) { alert(s); } })

That's all you need!


use the selector property:

var jQueryObject = $('my string');
var originalString = jQueryObject.selector;// it'll give you 'my string'


Is this what you're after?

$.fn.makeLower = function() { return this.selector.toLowerCase(); }

$("FOO").makeLower(); // produces "foo"
0

精彩评论

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

关注公众号