Javascript DOM最佳实践
嘿,我上面的代码处于if状态,我希望它更清晰,不重复,这样任何人都知道如何更干净。如果唯一区分图像的是图像的路径,我会将所有这些添加到数组中,然后使用索引查找它们Javascript DOM最佳实践,javascript,if-statement,dom,indexing,Javascript,If Statement,Dom,Indexing,嘿,我上面的代码处于if状态,我希望它更清晰,不重复,这样任何人都知道如何更干净。如果唯一区分图像的是图像的路径,我会将所有这些添加到数组中,然后使用索引查找它们 让imageSources=['https://media.s-bom.com', 'https://images-na.ssl-images-amazon.com', 'https://upload.wikimedia.orgmmer.jpg/220px-The_pragmatic_programmer.jpg']; const i
让imageSources=['https://media.s-bom.com', 'https://images-na.ssl-images-amazon.com', 'https://upload.wikimedia.orgmmer.jpg/220px-The_pragmatic_programmer.jpg'];
const image=document.createElement('img');
image.alt='image';
image.src=图像源[索引];
image.width='100';
李.儿童(图像);
因为唯一的区别似乎是src
只把它放在if()
里面。无需复制它的其余部分请注意,如果通过index=999
if (index === 0) {
const image = document.createElement('img');
image.alt = 'image';
image.src = 'https://media.s-bom.com';
image.width = '100';
li.appendChild(image);
}
if (index === 1) {
const image = document.createElement('img');
image.alt = 'image';
image.src =
'https://images-na.ssl-images-amazon.com';
image.width = '100';
li.appendChild(image);
}
if (index === 2) {
const image = document.createElement('img');
image.alt = 'image';
image.src =
'https://upload.wikimedia.orgmmer.jpg/220px-The_pragmatic_programmer.jpg';
image.width = '100';
li.appendChild(image);
}