简体   繁体   中英

Refactoring and DRYing up jQuery code

What I'm doing is adding a class to all elements who have the same class name as the id I'm hovering over. For example when I hover some list item with the id of vowel, then all the span elements with the class of the name vowel get acted upon (adding a class).

I can do that with no problems. But I want to do the same thing for many other id names with corresponding class names. Examples: consonants, semi-vowels, gutturals, palatals, etc.

I could do all these with different functions but I want to do is to call a function which will perform the same tasks but will be smart enough to find the name of the id and to generate the class name from that.

How do I extract the id name into a variable and assign it to the class name.

You could use a plugin:

$.fn.highlight = function() {
    return this.each(function() {
        $(this).hover(function() {
            var id = $(this).attr('id');
            $('.'+id).addClass('myclass');
        });
    });
}

Which you could call like this:

$(document).ready(function() {
    $('span').highlight();
});

You could do this:

$("[id]").hover(function() {
  $("." + this.id).addClass("highlight");
}, function() {
  $("." + this.id).removeClass("highlight");
});

but I wouldn't necessarily recommend it. I'd be more inclined to statically define it:

var ids = ["vowels", "consonants"];
for (var i = 0; i < ids.length; i++) {
  $("#" + ids[i]).hover(function() {
    $("." + this.id).addClass("highlight");
  }, function() {
    $("." + this.id).removeClass("highlight");
  });
}

or something like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM