开发者

Targeting multiple variables in jQuery

开发者 https://www.devze.com 2023-01-05 12:15 出处:网络
I know this is probably a very simple fix.I need to use 2 variables for this function and with the current code it on开发者_开发百科ly fires on the first variable.Variables MUST be used for the functi

I know this is probably a very simple fix. I need to use 2 variables for this function and with the current code it on开发者_开发百科ly fires on the first variable. Variables MUST be used for the function in question.

var a = $(h1), b = $(h2); 

    $(a, b).hover(function(){
        ...stuff happens here
    });

please DO NOT suggest something like the scenario below. variables NEED to be used.

$('h1, h2').hover(function(){...});


You don't need to wrap the variables with jQuery initially.

Assuming h1 and h2 represent DOM nodes:

$([h1, h2]).hover(function(){
    ...stuff happens here
});

We are passing an array as the jQuery function accepts an array of DOM elements. See docs.

See examples.


If for whatever reason you must work with separately assigned variables representing jQuery collections, you can add them:

var a = a.add(b);
$(a).hover(...

Also, don't forget you probably want $('h1'), not $(h1).

Here's a working fiddle.


a.hover(myHover);
b.hover(myHover);

function myHover(){
     alert('i wish you a happy hovering!');
}

the second parameter of the $ function defines the dom chunk for the search, if you leave it out it takes the hole document. so you better don't mess with, if you are trying to get all your elements on the page

0

精彩评论

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