简体   繁体   English

在 javascript 中编码的更有效方法

[英]more efficient way to code this in javascript

I am building a watch customizer for school, im pretty new to javascript, this code works but its lengthy, and i will need to add a lot more colours.我正在为学校构建一个手表定制器,我对 javascript 很陌生,这段代码有效但很长,我需要添加更多颜色。 is there a more efficient way to code this?有没有更有效的方法来编码?

each color change is being called from buttons if that helps.如果有帮助,将从按钮调用每个颜色更改。

thanks for any help in advance.感谢您提前提供任何帮助。

   ///////////////////////////////////////// Face
  function ChangeFaceRG()
    {
    document.getElementById('face').src = "parts/faces/face roesGold.png";
    };
 function ChangeFaceG()
    {
    document.getElementById('face').src = "parts/faces/face gold.png";
    };
 function ChangeFaceS()
    {
    document.getElementById('face').src = "parts/faces/face silver.png";
    };
///////////////////////////////////////// Frame
  function ChangeFrameRG()
    {
    document.getElementById('frame').src = "parts/frames/frame rosegold.png";
    };
 function ChangeFrameG()
    {
    document.getElementById('frame').src = "parts/frames/frame gold.png";
    };
 function ChangeFrameS()
    {
    document.getElementById('frame').src = "parts/frames/frame silver.png";
    };

    //////////////////////// Hands
  function ChangeHandsRG()
    {
    document.getElementById('hands').src = "parts/hands/hands rose gold.png";
    };
 function ChangeHandsG()
    {
    document.getElementById('hands').src = "parts/hands/hands gold.png";
    };
 function ChangeHandsS()
    {
    document.getElementById('hands').src = "parts/hands/hands silver.png";
    };
////////////////////////////////////////// straps
  function ChangeStrapsRG()
    {
    document.getElementById('straps').src = "parts/straps/straps rose gold.png";
    };
 function ChangeStrapsG()
    {
    document.getElementById('straps').src = "parts/straps/straps gold.png";
    };
 function ChangeStrapsS()
    {
    document.getElementById('straps').src = "parts/straps/straps silver.png";
    };

Consider a more generic approach考虑更通用的方法

Since all of your calls seem to do the same thing: target an image and set the source for it, you could likely refactor this out into a single function :由于您的所有调用似乎都在做同样的事情:定位图像并为其设置源,因此您可能会将其重构为单个函数:

function SetImage(id, imgSrc) {
    // Find the image by it's `id` attribute and then set the source for that image
    document.getElementById(id).src = imageSrc;
}

This would allow you to just specific the id of the element that you are targeting and then the path for your given image :这将允许您只指定要定位的元素的id ,然后指定给定图像的路径:

<!-- Example usage -->
<button onclick='SetImage("face","parts/faces/face roesGold.png")'>Change Face</button>

You need to pass arguments to the function to make it more reusable/modular.您需要将参数传递给函数以使其更具可重用性/模块化。

function ChangeHands(type) {
  document.getElementById('hands').src = `parts/hands/hands${type}.png`
}

Then you can call ChangeHands('rosegold.png')然后你可以调用ChangeHands('rosegold.png')

You can do this for each of the functions, ChangeFace, ChangeHands, ChangeFrame, and ChangeStraps.您可以为每个函数、ChangeFace、ChangeHands、ChangeFrame 和 ChangeStraps 执行此操作。 Cheers and great question!干杯和好问题!

If you're using es2015:如果您使用的是 es2015:

// Config object, here you create a map between the id and the path
const CONFIG = {
    face: 'faces/face',
    frame: 'frames/frame',
    hands: 'hands/hands',
    straps: 'straps/straps'
}

// Get the correct path based on the provided type and color
const getPath = (type, color) => `parts/${type} ${color}.png`;

// Apply transformation with the path obtained from the `getPath` function 
const change = function (type, color) {
    document.getElementById(type).src = getPath(CONFIG.type, color);
}

// Example usage:
change('face', 'roseGold');

Otherwise (if you're not using es2015) you can replace the functions to be something like this:否则(如果您不使用 es2015)您可以将函数替换为如下所示:

function getPath (type, color) {
    return ['parts/', type, ' ', color, '.png'].join('');
}

function change (type, color) {
    document.getElementById(type).src = getPath(CONFIG.type, color);
}

Or just concatenate string with '+' operand.或者只是将字符串与 '+' 操作数连接起来。

This approach tries to have smaller functions and ensures that each has a single responsibility.这种方法尝试使用较小的功能并确保每个功能都有一个单一的责任。

StackOverflow isn't a good place for such questions, because it could be solved in infinite different ways. StackOverflow 不是解决此类问题的好地方,因为它可以以无限不同的方式解决。 But, here you are, this is how I would do it:但是,在这里,我会这样做:

var arrayWithPaths = [
    "parts/hands/hands silver.png",
    "parts/straps/straps rose gold.png",
    //and all other paths here
];

function change(what, toWhat){
    document.getElementById(what+'').src = arrayWithPaths[toWhat];
}

what is a string with id of object you want to change. what是带有您要更改的对象的 id 的字符串。 You create array with all paths of images you want to use.您使用要使用的所有图像路径创建数组。 Then you can create toWhat variable to specify which one do you want to use calling change function.然后你可以创建toWhat变量来指定你想使用哪个变量来调用change函数。

For next level strats crate and array of all your conditions and loop through it.对于下一个级别的包装箱和所有条件的数组并循环遍历它。

ids = new arrary [id1, id2, id3, etc];
srcs = new arrary [src1, src2, src3, etc];
function setImage(id, imgSrc) {
    document.getElementById(id).src = imageSrc;
}
for(i=0; i<ids.length;i++){

setImage(id[i], src[i]);
}

arraies and cycles数组和循环

var ids = ["face", "frame", "hands", "straps"]
var colors = ["rose gold", "gold", "silver"] 

ids.forEach(function(id, i, ids) {
     colors.forEach(function(color, i, colors) {
            document.getElementById(id).src = "parts/hands/hands " + color +".png";
     });
});
function Change(folder, part, color) {
  document.getElementById(part).src = "part/" + folder + "/" + part + " " + color + ".png" ;
}

usage:用法:

Change('hands', 'hand', 'rose gold');
Change('frames', 'frame', 'silver');
Change('straps', 'strap', 'gold');
Change('faces', 'face', 'silver');

Should work, I think.应该工作,我想。

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

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