动态调用的函数,参数未定义

Dynamically called function, argument not defined

我正在动态生成一个画廊,每个画廊项目都有一个 onClick 事件,该事件调用一个以项目值作为参数的函数。

我测试了没有“ ”的代码,并且定义了值,但该函数在创建项目时运行,而不是在单击时运行。

当我使用“”时,函数仅在我单击它时运行,但我得到 未定义值

我想动态创建函数,并使用值作为参数在单击时触发它。

jsGallery 是一个数组,我循环使用它来构建图库项目。

图库项目代码

function createDiv(type) {
  jsGallery.forEach((item) => {
    if (item.type === type) {
      let newDiv = document.createElement("div");
      newDiv.setAttribute("value", item.id);
      newDiv.setAttribute("class", "item" + " " + type);
      newDiv.setAttribute("id", "dynamic");

      newDiv.setAttribute("onClick", "testFire(value)");

      document.getElementById("galleryContainer").appendChild(newDiv);
    }
  })
}

TestFire 函数

function testFire(value) {
  console.log(value);
}

testFire (value) 的参数是一个不存在的绑定,这就是它 returns 未定义的原因。

而不是

newDiv.setAttribute("onClick", "testFire(value)");,

做:

newDiv.onclick = () => testFire(newDiv.value);

顺便说一句,它仍然返回 undefined 因为 div-元素只有 global attributes.

谢谢 Andre Nuchter,我使用了您的方法,但由于值仍未定义而返回,因此稍微更改了它。

newDiv.onclick = () => testFire(item.id);