JQuery selector question for classes / ids containing the same number
My website has a set of elements with the classes "element1", "element2", "element3", etc, and also another set containing elements with the classes "1", "2", "3". These开发者_JAVA百科 are not directly related in the DOM so I cannot use parent / child selectors.
I want to write a JQuery script that, when the user hovers on "element1", triggers an effect / function in "1".
Of course, I don't want to write all the pairings manually. How could I write this code so the selectors "detect" the number in the class names? Do I need to use regular expressions?
I can change my HTML if needed.
If you want to use just one bit of code to effect all of your elements something like this should do:
$('.hover').hover(function() {
var element = $(this).attr('class').replace(' hover', '');
element = element.replace('element', '');
$('.'+element).slideToggle();
});
You need to add the class hover to all your elements you want it to work on, it will then get the element number, and toggle that element.
This could be a sample HTML
<a href="#" class="element1 hover">Element 1</a><br/>
<a href="#" class="element2 hover">Element 2</a><br/>
<div class="1 hidden">You are hovering over element 1</div>
<div class="2 hidden">You are hovering over element 2</div>
See here for a demo
And a commented demo here
If all your IDs are simply elementX
, you could get the class by using String.prototype.replace
without regular expressions:
// `this` refers the DOM element in question
var class = this.id.replace('element', '');
Imo it is better to give your elements class names that not only consist of a number.
The best way is to give all those elements that have this kind of ID a class too:
$('.someclass').hover(function() {
$('.' + this.id.replace('element', '')).something();
});
You can try doing
$("[id^='element']")..
or do it using a loop
for (i = 0; i < 10; i++) {
$('element' + i)..
}
精彩评论