简体   繁体   中英

call a function inside innerHTML

I need to call a function inside innerHTML and this is my try but it doesn't work.

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")
}

Here is the HTML Part:

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

Variables in onclick attributes are evaluated in the global scope, you can't refer to local variables. You need to replace id in the string with the actual value of the id variable. You can do this with a template literal.

 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; dg = d.getElementById; let res = dg('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> 

While innerHTML is easy to use, according to a discussant here :

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

So, instead of solving the OP's query with respect to innerHTML , this solution purposefully avoids it by utilizing DOM manipulation and at the same time makes the desired function available as a handler for an onclick event of an <LI> element. To achieve this end, the code creates a document fragment object . As a result the code is able to add the LI elements as well as the id of each one and set the onclick event-property of each in a function invoked by the docs.forEach() . Also, I added some CSS to enhance the cursor when user clicks "Joe" or "Fred".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM