To achieve this you can use call()
to set the scope of the function you invoke.(为此,您可以使用call()
设置您调用的函数的范围。)
Also note that your $.fn.foo
function definition requires two arguments, not one.(还要注意, $.fn.foo
函数定义需要两个参数,而不是一个。) I used the first one as the classname to apply to the element in this example.(在本示例中,我将第一个用作类名称以应用于该元素。)
$.fn.foo = function(params, callback) { if (typeof callback === 'function') { callback.call(this, params); } } $('table tr').foo('foo', function(classname) { $(this).addClass(classname); });
.foo { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td>Foo</td> </tr> </table>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…