开发者

Use jQuery .find() result as argument in callback function in chain

开发者 https://www.devze.com 2023-03-25 05:17 出处:网络
I have this problem (is it now?): Let\'s have this HTML: <div> <p></p> <p id=\"bar\"></p>

I have this problem (is it now?):

Let's have this HTML:

<div>
 <p></p>
 <p id="bar"></p>
</div>
<div>
 <p id="foo"></p>
 <p id="baz"></p>
</div>

simple.

In jQuery, we have function (e.g. 'click') added to all divs:

$('div').click(function(){
  $(this).doSomething($(this))
  .find('#baz')
    .doSomethingWithCallback ({args}, callbackFunction($FIND_RESULT) );
});

Obviously, variable $FIND_RESULT doesn't exist – I would like to know how can I get to result of last .find() query?

Is there any way, or do I have to break my mad chain (or repeat $(this).find() as argument)?

Edit: IRL example:

开发者_如何学运维function hide($div) { $div.css({'display': 'none'});

function ...
  $(this)
    .anyFunction()
  .find('.foo')
    .animate({opacity: 0}, 250, hide(^that^));
 }


Generally with jQuery functions, your doSomethingWithCallback will be executed multiple times one for each match of find(), and therefore your callback method will be called one time for each match too, so passing the set of elements is innecesary, use $(this).


I'm a bit confused also. The .find() method is extremely robust, so are all the other jQuery functions. Each one executes on a group of elements and then passes those elements back so that other functions can chain on them. http://jsfiddle.net/rkw79/DXbXU/

On your custom function, are you returning the objects after you process them? http://docs.jquery.com/Plugins/Authoring#Maintaining_Chainability


Are you looking for jQuery's

end()

?

If you're making you own plugins then take a look at pushSack() and end()

function ...
  $(this)
    .anyFunction()
  .find('.foo')
  .end()  // <---
    .animate({opacity: 0}, 250, hide(^that^));
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号