开发者

How to chain an anonymous function in jQuery?

开发者 https://www.devze.com 2023-01-29 08:07 出处:网络
I am trying to chain an anonymous function in jQuery but it\'s not working. I get an error \"Error: XML filter is applied to non-XML value ...\". What\'s the proper syntax or is there an effect functi

I am trying to chain an anonymous function in jQuery but it's not working. I get an error "Error: XML filter is applied to non-XML value ...". What's the proper syntax or is there an effect function I can use which doesn't do anything visually and which wraps my function开发者_如何学JAVA?

My example: $item.appendTo($list).(function() {.....}());


Chaining works by returning the original jQuery object as a result of invocation of the given chainable function. Hypothetically, to chain your anonymous functions, you must 'return' the original jQuery object.

However, your function has to be callable from the context of the jQuery object. For example, there exists the function

$item.appendTo

However, there is no function on the jQuery object that is reachable by:

$item.(function(){ })

Think of it like this. Let us say you have the following object:

var obj = { foo: function(){ console.log(1); } };

The 'foo' declaration is accessible as a property/declaration on obj. But what, exactly, is the declaration you are referencing with an anonymous function?

obj.(function(){ })

The only way you could give your anonymous function an execution context of the jQuery object, would be to do a 'call' on it

(function(){ }).call($item, args);

If you were wanting to chain this, you could theoretically do so by:

(function(){ return this; }).call($item, args).appendTo($other);

But I'm not sure what you'd gain. Your best bet is to simply do:

$item.appendTo($list);
(function($obj){ })($item);

Or, if you are starting off with a selector:

var $item = $('#someID').appendTo($list);
(function($obj){ })($item);

Though, at this point anonymous functions aren't as useful, so I would simply:

var someFunc = function($obj){ };
$item.appendTo($list);
someFunc($item);


you can use the .each method

$item.appendTo($list).each( function() {.....} );

Alternatively you can extend the jquery object with your own functions (jQuery.fn.extend()).

$.fn.extend({
    myOwnFunc: function(){
         /*do whatever*/
         return this; // to allow for further chaining.
    }
});

and now you can call $item.appendTo($list).myOwnFunc()


Shouldn't it be:

$item.appendTo($list).(function() {.....})();

Totally forgot to mention returning $;

0

精彩评论

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

关注公众号