开发者

jQuery without chain?

开发者 https://www.devze.com 2022-12-14 07:01 出处:网络
I know it\'s possible to write jQuery in more JavaScript like syntax rather than the all chain s开发者_运维百科tuff (which is great). It\'s hard to find a piece of tutorial that provide an understandi

I know it's possible to write jQuery in more JavaScript like syntax rather than the all chain s开发者_运维百科tuff (which is great). It's hard to find a piece of tutorial that provide an understanding for people who want to use less chain-able script, so where I can find any type of tutorial(s)?

While the chain was not bad, it requires a learning curve for being effective & efficient. I have some experience in JavaScript so it would be great if I could re-use my existing knowledge (a.k.a laziness to learn something new on strict and fast moving work environment).

PS: I usually use a less chain framework such as Adobe Spry Framework (dead, sadly), so I hope I could finf some similar approach in writing code on jQuery.


Since each part of the chain returns a jQuery object, you can break the chain up into separate pieces.

So, this...

$("<div>inner</div>")
    .appendTo("<div>outer</div>")
    .appendTo("body");

Is exactly the same as:

var myDiv = $("<div>inner</div>");
myDiv.appendTo("<div>outer</div>");
myDiv.appendTo("body");

But believe me, once you get used to it, it will become second nature. Check out this article for some more advice...


The great thing about jQuery is that most functions of the core jQuery object will return another jQuery object with the same functions available. So you can do this

var image = $("#myImage").attr("alt", "The Logo");
image = image.css("logoImage");

But it's much easier to do this

$("#myImage").attr("alt", "The Logo").css("logoImage");

because you cut out the intermediate steps.

It's worth persevering with the chaining, check out the Getting Started with jQuery tutorial.


Chaining is just using the result of one expression as input in another. They can easily be flattened to separate statements.

In case a method returns the same collection, you can just call the method as any other method:

var links = $('a.popup');
var handler = function(e){ window.open(this.href,this.target); e.preventDefault(); };
links.click(handler);
links.css('color', 'red');

If a method returns a different collection, you have to assign the return value to a new variable, or back to the same variable replacing the current collection:

var links = $('a.popup');
links = links.filter('[target=_blank]');
links.css('font-weight', 'bold');


It's doubtful you'll find such documentation.

Just replace the chained calls with the proper selectors.

$('#myId').call(blah)
          .chain(blah)
          .chain(blah)

with

var $obj = $('#myId');
$obj.call(blah);
$obj.chain(blah);
...
0

精彩评论

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

关注公众号