简体   繁体   中英

jQuery - Call a function on an element

I want to call a function to show and modify content like this:

$('#element').someFunction();

I wrote this function:

function someFunction(){
     $(this).show();
     //other stuff
}

But this don't work. Can someone give me a hint how to solve this.

You could extend jQuery and create a custom method:

 $.fn.someFunction = function() { return this.hide(); }; $('.element').someFunction(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="element">This should be hidden.</div> <div class="element">This should be hidden.</div> 

Internally .hide() will iterate over each element, but if you want to do this manually, you could just utilize the .each() method:

$.fn.someFunction = function() {
  return this.each(function() {
    // 'this' refers to the element here
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM