在 innerHTML 中调用一个函数

call a function inside innerHTML

我需要在内部调用一个函数HTML,这是我的尝试,但它不起作用。

category.find({}, function(err, docs) {
    docs.forEach(function(d) {
          var id = d._id
          document.getElementById('result').innerHTML += '<li onclick=insert(id)>' + d.name + '</li>'
    })
})

function insert(id){
  alert(id + "Inserted")
}

这是HTML部分:

<div id="result"></div>

onclick 属性中的变量在全局范围内计算,不能引用局部变量。您需要将字符串中的 id 替换为 id 变量的实际值。您可以使用模板文字执行此操作。

const docs = [{
  id: "FgrbV2NTp72ie6xj",
  name: "Joe"
}, {
  id: "agfadsfasdfq23",
  name: "Fred"
}];

docs.forEach(function(d) {
  document.getElementById('result').innerHTML += `<li onclick="insert('${d.id}')">${d.name}</li>`
});

function insert(id) {
  alert(id + " Inserted")
}
<ul id="result"></ul>

const docs = [{
  id: "FgrbV2NTp72ie6xj",
  name: "Joe"
}, {
  id: "agfadsfasdfq23",
  name: "Fred"
}];
let d = document;
d.g = d.getElementById;
let res = d.g('result');

let fragment = new DocumentFragment();
let el = null;
docs.forEach(function(item) {
  el = document.createElement('li');
  el.innerText = `${item.name}`;
  el.onclick = function(){
     alert(`${item.id}` + " Inserted");
  };
  fragment.appendChild(el);
});

res.appendChild(fragment);
ul{
cursor:default;
}
<ul id="result"></ul>

虽然 innerHTML 易于使用,但根据讨论者 here 的说法:

...in general, .innerHTML is for small fragments of HTML to be inserted and parsed into a document ..

因此,此解决方案不是解决 OP 关于 innerHTML 的查询,而是通过利用 DOM 操作有目的地避免它,同时使所需函数可用作处理程序

  • 元素的 onclick 事件。为此,代码创建了一个 document fragment object。因此,代码能够添​​加 LI 元素以及每个元素的 ID,并在 docs.forEach() 调用的函数中设置每个元素的 onclick 事件-属性。此外,我添加了一些 CSS 以在用户单击 "Joe" 或 "Fred" 时增强光标。