【问题标题】:Javascript DOM best practiceJavascript DOM 最佳实践
【发布时间】:2021-05-30 19:35:39
【问题描述】:
 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);
    }

嘿,我在 if 条件下有上面的代码,我希望它更清晰而不是重复,所以任何人都知道如何更干净。

【问题讨论】:

  • 因为唯一的区别似乎是src 只把它放在if() 里面。无需复制其余部分

标签: javascript if-statement dom indexing


【解决方案1】:

如果唯一将图像区分开来的是图像的路径,我会将所有这些添加到一个数组中,然后使用索引查找它们。

let 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 = imageSources[index];
image.width = '100';
li.appendChild(image);

【讨论】:

  • 请注意,如果通过 index=999,则其行为与 OP 的代码不同
猜你喜欢
  • 1970-01-01
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多