Get Dom element from jquery plugin extension

I am trying to get the dom element from a jquery extension. This allows the user to do the following

if i,

("#content").myPlugin.myMethod(myValue); 

I would like to:

 $.fn.myPlugin.myMethod = function (myValue) { $(this).html(myValue); } 

This is a basic example of what I'm trying to achieve. Although "this" is not a Dom element, but a myPlugin function.

how can i access #content?

Yours faithfully,

theHaggis

+4
source share
4 answers

The “standard” idiom is to use the each () method:

 $.fn.myMethod = function(myValue) { return this.each(function() { $(this).html(myValue); }); }; 

This way you can maintain jQuery objects containing multiple elements and chain at the same time.

+3
source

Example 1

To use the selector used in your plugin, use:

 this.selector 

Example:

 $.fn.myPluginMethod = function(myValue) { $(this.selector).html(myValue); } $("#content").myPluginMethod("Hello World"); 

Demo Screenshot: http://jsfiddle.net/nJeeH/

Example 2

The only other solution is to create a faux myPlugin method that simply returns a jquery object to support the chain, but that does not stop you from just making $("#content").myMethod("Hello World"); instead of this.

 $.fn.myPlugin = function(myValue) { return this; } $.fn.myMethod = function(myValue) { this.each(function() { $(this).html(myValue); }); } $("#content").myPlugin().myMethod("Hello World"); 

Demo Screenshot: http://jsfiddle.net/nJeeH/1/

0
source

the function (your plugin) is assigned by myMethod , and myMethod is called by myPlugin , so when executed

 $("#content").myPlugin.myMethod(myValue); 

the keyword "this" will be pointed to myPlugin .

you can see here for more information: what does this mean in javascript

you can put your method in your plugin and provide a way to call it, for example

 $("#content").myPlugin('myMethod',parametersArray); 
0
source

You can use closure and the bind () primitive to scale functions in JS:

var myMethod = function (myValue) {$ (this) .html (myValue); }

 $.fn.myPlugin = function() { var jq = this; return { myMethod : myMethod.bind(jq) } } $("#content").myPlugin().myMethod('eh oh!'); 

Nb: it's easier to change the scope of functions using closure than using a prototype

0
source

Source: https://habr.com/ru/post/1389654/


All Articles