How do I write .level+1 as a selector in JQuery or JavaScript?
A quic开发者_Python百科k question. I have a series of DIVs with the following classes .level1
.level2
.level3
This is what I want to happen...When I hover over .level1
I would like the selector to select .level2
. In other words .level
+1 whatever I hover over.
How do I write this in JavaScript or JQuery ...The X in the code is where I need this to go
$(".no-submenu").hover(function() {
$.data(this, "timer", setTimeout($.proxy(function() {
$( X ).hide();
}, this), 700));
}, function() {
clearTimeout($.data(this, "timer"));
});
Any help is greatly appreciated, Thanks
If they're in order you can use .next() with a starts with attribute selector
$(this).next('[class^=level]').hide();
jsFiddle example
You can do a replacement with a function:
edit: added in the +
to support multi digit levels
function replacer(num) {
return (parseInt(num, 10) + 1);
}
var selector = $(this).attr("class").replace(/([\d]+)$/,replacer);
$("." + selector).hide();
So, in the case above X = "." + selector
simplified jsFiddle example
.replace()
.parseInt()
The above will work based purely on class names.... so the order of the DIVs is not important. If you know the order of the divs, you could use the jQuery .eq() selector.
I didn't test it, but just what I thought of
var x = 1; // You are probably going to change this
$('.level'+x).hover(function() {
$('.level'+(x+1)).dosomething();
},function () {
$('.level'+(x+1)).dosomethingelse();
});
精彩评论