Javascript 如何将这些类似的函数合并为一个

Javascript 如何将这些类似的函数合并为一个,javascript,function,refactoring,Javascript,Function,Refactoring,我一直在尝试将注意力集中在Javascript上,一直在寻找一种方法,将其转换为一个只影响当前悬停的DOM元素(我也通过createElement使用Javascript创建了DOM元素)的函数。我试过了。target和currentTarget的东西,没用。如果有人能为我指出正确的方向,我将永远感激 /* This first function is the experimental one, I tried this but to no avail */ function displayTo

我一直在尝试将注意力集中在Javascript上,一直在寻找一种方法,将其转换为一个只影响当前悬停的DOM元素(我也通过createElement使用Javascript创建了DOM元素)的函数。我试过了。target和currentTarget的东西,没用。如果有人能为我指出正确的方向,我将永远感激

/* This first function is the experimental one, I tried this but to no avail */
function displayTooltip1(tt) {
    var x = tt.currentTarget;
    x.style.cssText = "width: 100px; height: 100px; display: inline-block; margin: 0;1.5px 0 1.5px; overflow: visible;"
}

function displayTooltip2() {
    document.getElementById('image2').style.cssText = "width: 100px; height: 100px; display: inline-block; margin: 0 1.5px 0 1.5px; overflow: visible;";
}

function displayTooltip3() {
    document.getElementById('image3').style.cssText = "width: 100px; height: 100px; display: inline-block; margin: 0 1.5px 0 1.5px; overflow: visible;";
}

只需传递组件的id并通过该id获取组件

使用方法如下:

function displayTooltip(componentId) {
    document.getElementById(componentId).style.cssText = "width: 100px; 
    height: 100px; display: inline-block; margin: 0 1.5px 0 1.5px; overflow: visible;";
    }

正如我所看到的,您的所有函数都做相同的事情,但使用不同的元素,因此您可以创建一个函数,该函数将接受元素ID,并使用该元素更改样式:

function displayTooltip(id){
    document.getElementById(id).style.cssText = "width: 100px; 
    height: 100px; display: inline-block; margin: 0 1.5px 0 1.5px; overflow: visible;";
}

displayTooltip(tt);
displayTooltip('image2');
displayTooltip('image3');

不过,谢谢你,请原谅我问这个问题:我将如何使它充满活力?我应该用什么来代替“componentId”?因为有8个不同的ID。在调用函数时,请指定目标的ID。e、 g.hover target您可以在创建动态元素时指定mouse over的函数。看看吧,很高兴它对你有帮助。你可以接受答案并投票表决。嗨,首先谢谢你的打扰!第二,我如何让它识别哪一个正在激活该功能?也就是说,选择哪个参数值?很简单,你需要使用元素的ID,你想要改变的样式,就像一个魔咒!