具有太多参数的函数。如何使用和调用对象文字作为参数

问题描述 投票:1回答:1

我有一个将元素追加到页面的功能。这个函数在多个地方被调用,因此我的类名称由bootstrap完成,因此我为类名称设置了参数。

由于我多次调用该函数,因此为参数填写值可能会造成混淆,并容易出错。

我当时想使用object literal。我不确定该怎么做,也不知道如何调用这样的函数。

我的功能:

const my_func = (a, b, c, d, e, f, g = true) => {
$(a).append(`
<div class='${b}'>${f}</div>
<input class='${b}'> />
<button class='${c}'></button>
if(g) {
  .....
}
`);
}
javascript jquery function ecmascript-6 object-literal
1个回答
0
投票

为了组织功能,您可以简单地通过基本分配destructure输入,然后每次调用它时,都可以用冒号(:)指定每对输入参数及其值。

所以我只是稍微修改了您的代码,并向其中传递了一些虚拟值。

const my_func = ({
  a,
  b,
  c,
  d,
  e,
  f,
  g = true
}) => {
  let html = `<div class='${b}'>${f}</div>
              <input class='${b}'/>
              <button class='${c}'>${d}</button>`;

  if (g) {
    html += '<div>g is true</div>'
  }

  $(a).append(html);
}

const container = $(".container");
my_func({a: container, b: "red", c: "bold", d: "submit", f: "this is a division", g: true})
.red {
  color: red;
}

.bold {
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container"></div>
© www.soinside.com 2019 - 2024. All rights reserved.