Call jQuery function from JavaScript

I have jQuery code:

$(function(){ 
function someFunc(){
    /*do something*/
};
.............   
});

And now I want to call someFunc from JavaScript, as shown below:

function test(){    
$.fn.someFunc();
}

But that will not work! I saw an article on how to call a function in jquery from javascript . Is it possible?

+5
source share
3 answers

A simple definition of a function in a closure (function) that you pass in $()does nothing to put it in a jQuery object fn. To do this, you need to do this explicitly:

$.fn.someFunc = someFunc;

Typically, you would not do this in the callback to $(); you would have done this earlier. Plugins do this to add functionality that must be present before the DOM is ready.

, , :

(function($) {
  $.fn.green = green;
  function green() {
    return this.css("color", "green");
  }
})(jQuery);

... DOM:

jQuery(function($) {

  $(".foo").green();

});

| Live source

, jQuery, $.fn.

+5

someFunc " jQuery", , (jQuery) DOMContentLoaded.

, . , :

$(function(){ 
    // nothing here , but you can call someFunc() if you want
});

function someFunc(){
    /*do something*/
};

function test(){    
    someFunc(); // works!
}
+1

jquery

$.fn.someFunc = myFunc;
function myFunc()
{
    // Code here
}

javascript

function myObj()
{
    // Code here
}
var obj= new myObj();
obj.prototype.someFunc=myFunc;
function myFunc()
{
    // Code here
}

( ), jquery fn - javascript. sumFunc, jquery,

$.fn.someFunc = myFunc;

$('someElement').someFunc();

and this line will call the taht function and do something with "someElement" (although I didn’t do anything), hope this is clear enough. Take a look at TJ Crowder's answer, this will give you some insight.

+1
source

All Articles