BACKGROUND: I have nine divs with classes .big1, .big2, .big3, and .small1, .small2, .small3. The divs aren't siblings or parents & children, or I'd be doing this with pure CSS.
I'm adding a class to .big1 when .small1 is hovered over, and .big2 when small2 is hovered over. My current approach (shown below) works but is inelegant. Though I'm pretty new to jQuery, I believe it's possible to shrink the code down to a single .addClass function, using variables to change the class names accordingly.
PROBLEM: I'm trying to set up my code so the number x on the end of a hovered .big*x* div is appended to the class name of the .small*x* div that follows, probably by creating a variable out of the numbers on the .big and .small classes. This is where I'm stuck. I've looked at using .split() to grab the number at the end of a .small and .replace() to put that number on the end of the .big, but I can't figure out how to set it up. Suggestions are appreciated!
jQuery:
$('.small1').hover(
function(){
$('.big1').addClass("itemHover");
},function(){
$('.big1').removeClass("itemHover");
});
$('.small2').hover(
function(){
$('.big2').addClass("itemHover");
},function(){
$('.big2').removeClass("itemHover");
});
$('.small3').hover(
function(){
$('.big3').addClass("itemHover");
},function(){
$('.big3').removeClass("itemHover");
});
Simplified HTML: (again, the divs in my markup aren't siblings or parents/children)
<div class="big1"></div>
<div class="big2"></div>
<div class="big3"></div>
<div class="small1"></div>
<div class="small1"></div>
<div class="small2"></div>
<div class="small2"></div>
<div class="small3"></div>
<div class="small3"></div>
UPDATE/SOLUTION: This is just to clarify a couple of lines in @Sergio's solution. There were a couple of missing brackets that were breaking the code in FF. The solution below was successfully tested in IE 10, Chrome and FF:
$('div[class^="small"]').hover(function () {
var this_class = $(this).prop('class');
var filter = $.grep(this_class, function (a) {
return a ^= 'small';
});
$('div.big' + filter).addClass("itemHover");
}, function () {
$('div[class^="big"]').removeClass("itemHover");
});
Not sure how your html looks like but this can be useful:
Option 1: (this works with different classes)
$('div[class^="small"').hover(function () {
var filter = $.grep(this.className.split(' '), function(a) {
return a.indexOf('small')===0;
});
filter = filter[0].split('small')[1];
$('div.big' + filter).addClass("itemHover");
}, function () {
$('div[class^="big"').removeClass("itemHover");
});
Demo here (hover with mouse over S1
)
Option 2:
var all_BIG = $('div[class^="big"');
var all_small = $('div[class^="small"');
all_small.hover(function () {
var this_ind = $(this).index();
all_BIG.eq(this_ind).addClass("itemHover");
}, function () {
all_BIG.removeClass("itemHover");
});
Demo here (hover with mouse over S1
)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加