Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

javascript - 如何在jQuery函数的回调中引用元素?(How to reference element in a jQuery function's callback?)

Let's say I have a jQuery function like this:(假设我有一个这样的jQuery函数:)

$.fn.foo = function(param, callback) { if (typeof callback === 'function') { callback(params); } } and then when calling the function on an element like:(然后在类似这样的元素上调用函数时:) $('table tr').foo(bar, function(param) { console.log($(this)); // this needs to reference 'table tr' }); In cases like this, I've noticed that this references the window.(在这样的情况下,我注意到this引用窗口。) How would you reference the element that the function is being called on without passing it as an argument inside the callback?(如何在不将其作为参数传递给回调内部的情况下引用要调用该函数的元素?)   ask by Amir Rami translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...