0

I have being fighting with this issue for a couple of days now, I'm using eval() to declare some variables that come from firebase. I want to make a clickable url that might allow me to select between different files of the DB.

function Versiones(doc) {
  Layout_02.innerHTML += `
    <p id="${doc.id}"> Id= ${doc.id} </p>
    <p> OT= ${doc.data().OT} </p>
    <p> Entrega= ${((doc.data().Entrega).toDate()).toDateString()} </p>
    <p> Registrado= ${((doc.data().Generada).toDate()).toDateString()} </p> `;

  eval(`const ${doc.id} = document.getElementById("${doc.id}");`);
  eval(`${doc.id}.addEventListener("click", ()=>{Documento(${doc.id})});`);
}

function Documento(doc) {
  console.log("Recibido: ");
  console.log(doc.id);
}

The thing is that, just the last paragraph actually have a click event associated, the other paragraphs doesn't have. Can you help me understand what is happening ?

I have tried changing the variable type, and using onclick event. but nothing works.

Thanks.

Mohammed Shahed
  • 840
  • 2
  • 15
  • You may be interested to see this: https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – user3425506 Nov 17 '22 at 17:25
  • **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()` - [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) – ThS Nov 17 '22 at 17:25
  • I do not understand your code but it looks odd that you define a function called *Versiones* and do not call it. Then you call *Documento* which is not defined. Why is that please? – user3425506 Nov 17 '22 at 17:28
  • See [“Variable” variables in JavaScript](/q/5187530/4642212). In practice, you never need — or _want_, really — dynamic variable names. Use a simple object instead: `const obj = { [doc.id]: document.getElementById(doc.id) };` … `console.log(obj[doc.id]);`, or, for indexed structures, an array. Use [event delegation](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of adding several event listeners — it’s more maintainable and applies to dynamically added elements. See [this info](/tags/event-delegation/info) and [this Q&A](/a/55452921/4642212). – Sebastian Simon Nov 17 '22 at 17:33

0 Answers0