简体   繁体   English

重构和干燥jQuery代码

[英]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. 我正在做的是将一个类添加到所有具有与我悬停的id相同的类名称的元素。 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). 例如,当我将某些列表项悬停在具有元音ID的列表项上时,具有名称为vowel的类的所有span元素都将受到作用(添加一个类)。

I can do that with no problems. 我可以做到这一点没有问题。 But I want to do the same thing for many other id names with corresponding class names. 但是我想对具有相应类名的许多其他id名称执行相同的操作。 Examples: consonants, semi-vowels, gutturals, palatals, etc. 例如:辅音,半元音,首尾音,pa音等。

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. 我可以使用不同的函数来完成所有这些操作,但是我想做的是调用一个函数,该函数将执行相同的任务,但会足够聪明地找到id的名称并从中生成类名。

How do I extract the id name into a variable and assign it to the class name. 如何将ID名称提取到变量中并将其分配给类名称。

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. 或类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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