How to create your own function in jQuery?

How to create your own function and call it another function? as -

$('.mycls li').hover(function() {    
var divid = $(this).find('li').attr('some_attr');
call myfunc(divid);
});

function myfunc(divid)
{
$(divid).show();
//I want to hide rest all divs 
$('div#info1').hide();
$('div#info2').hide();
$('div#info3').hide();
}

I have 2 questions: how to implement this logic in jquery second, which attribute can be used to reference a specific li to a specific div

my divs are equal -

<div id="info1">
//some information
</div>
<div id="info2">
</div>
....
+3
source share
3 answers

Your functions should be able to work with a wrapped set similar to other jquery methods / functions. Consider the plugin, it's easy:

jQuery Plugin Tutorial

Or see:

Defining your own functions in jQuery

+5
source

There is no keyword callto use to call the function. Therefore just using

myfunc(divid);

to call your function.

li -s div -s, , , li -s div, "info", , .

<li id='d1'> </li>
<li id='d2'> </li>
<li id='d3'> </li>

<div id='info1'></div>
<div id='info2'></div>
<div id='info3'></div>

$('.mycls li').hover(function() {      
    // get the number part of the li id and use it to
    // build the divid by appending it to "info"
    var divid = "info" + $(this).attr('id').slice(1);
    myfunc(divid);   
});   

function myfunc(divid)   
{
     $("#" + divid).show();   
     //hide all divs that do not have id=divid
     $("div:not(#" + divid + ")").hide();
} 
+1

I wrote the following:

jQuery.fn.doSomeStuff = function(options, callback) {
    var $elem = $(this[0]) 
    var args = options || {};

    // doSomeStuff
    alert("DOM element: "+$elem.html());
    alert("this ia a parameter:"+ args.aParameter);

    if (typeof callback == 'function') { // make sure the callback is a function
        callback.call(this); // brings the scope to the callback
    }
    return $elem; //ensures jquery chainability
};
  • define your own function
  • specify parameters and callback
  • provide jquery chaining

You can try here

+1
source

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


All Articles