簡體   English   中英

如何在jQuery中使用$(this)改進此代碼?

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

我有以下jQuery函數(簡體):

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

不用擔心.text()部分,實際上我正在做的事情比那還要復雜...但是由於這與我的問題無關,因此我僅在此處使用.text()作為簡單示例。

問題是,每當我調用doSomething()函數時,代碼如下所示:

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

如您所見,我總是將$(this)作為第一個參數。 某種程度上,我覺得這不是走的路...可以改進此功能,以便它自動從調用它的上下文繼承$(this)嗎? 也許像下面這樣:

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

您可以創建一個簡單的插件來執行此操作。

關於很多文章。 有關更多信息,請參見jQuery網站上的這一本書

$(function(){

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

});

然后調用它

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

似乎您需要類似jquery插件的功能。

(function($){

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

      doSomething: function(options) {

        return this.each(function() {

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

        });
    }
});

})(jQuery);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM