简体   繁体   中英

How to improve this code using $(this) in jQuery?

I have the following jQuery function (simplified):

function doSomething(el, str) {
 el.find('.class').text(str));
}

Don't worry about the .text() part, in reality I'm doing something a bit more complicated than that... But since that's irrelevant to my question, I'm just using .text() here as a simple example.

The problem is, everytime I'm calling the doSomething() function, the code looks like this:

doSomething($(this), foo); // the second argument is irrelevant
doSomething($(this), bar); // the second argument is irrelevant

As you can see, I'm always passing $(this) as the first argument. Somehow I feel this is not the way to go... Can this function be improved so it automatically inherits the $(this) from the context where it's called? Maybe something like the following:

$(this).doSomething(foo); // the foo argument is irrelevant
$(this).doSomething(bar); // the bar argument is irrelevant

You can create a simple plugin to do this.

Lots of articles about. See this one on the jQuery site for more info

$(function(){

   jQuery.fn.changeAnchorText = function(str) {
     return this.each( function(){
        $(this).find('a.someClass').text(str);
     });
   };

});

then to invoke it

$('div').changeAnchorText("Any descendant anchor tags inside this div with a class of someClass will have the text changed to this message");

seems you want something that works like jquery plugin.

(function($){

//Attach doSomething method to jQuery
$.fn.extend({ 

      doSomething: function(options) {

        return this.each(function() {

          var el = $(this);
          // do something here

        });
    }
});

})(jQuery);

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