我有以下 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
最佳答案
您可以创建一个简单的插件来执行此操作。
很多关于的文章。请参阅this有关更多信息,请访问 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");
关于javascript - 如何在 jQuery 中使用 $(this) 改进此代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1244075/