开发者

Using 2 variables at the same time

How do I go about doing this?

$(function() {

   var foo = $('#foo'),
       bar = $('#bar');

    $('body').click(function() {

        $(foo,bar).css({color: 'red'}); 

    });

});

Demo: http://jsfiddle.ne开发者_C百科t/each/RGZ4Z/ - Only foo becomes red

Edit: Can i stress the fact that I'm aware I could easily do:

$('#foo,#bar').css({color: 'red'});

I'm simply asking about the usage of variables...


Probably, what you want is this:

foo.add(bar).css({color: 'red'});

Here's a demo piece of code that shows how this can work: http://jsfiddle.net/jfriend00/3Ep6J/.

There are three choices I can think of depending upon what you want:

  1. var items = $('#foo, #bar')
  2. $('#foo, #bar').css({color: 'red'});
  3. foo.add(bar).css({color: 'red'});

And, more detail on each option:

1) You can either just create one jQuery object in the beginning that has both sets of objects in it like this:

var objs = $('#foo, #bar');

and then later do this:

objs.css({color: 'red'}); 

2) Or just do it all at once:

$('#foo, #bar').css({color: 'red'}); 

3) Or, if you already have separate jQuery objects for foo and bar, you can add the items from one jQuery object to the other and then carry out your operation:

var foo = $('#foo'),
    bar = $('#bar');

and then later, do this:

foo.add(bar).css({color: 'red'}); 

Note: somewhat counterintuively, option 3) does not modify the foo jQuery object, the add method returns a new jQuery object with the items from bar added to it.


+1 to jfriend00's answer, but I thought I'd chime in to explain why yours wasn't working in the first place.

The jQuery "constructor" has three method signatures (essentially):

  1. $(selector[, context]) for creating a jQuery object out of existing elements
  2. $(html[, ownerDocument]) for creating new elements
  3. $(callback) as an alias for $(document).ready(callback)

You're using the first option, and selector is a pre-existing jQuery object (which is fine), however by adding the bar argument, that means that it is treating that element as the context. Essentially: "give me a result set containing all the elements foo which exist inside the element bar".

Also, if you know that you already have a jQuery object in a variable, it's just wasteful to wrap it another call to $().

bar = $('#bar');
$(bar).show();  // unnecessary!
bar.show();     // better!

To help me remember, I always prefix jQuery variables with $:

$bar = $("#bar");
$bar.show(); // less ambiguous! woo!
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜