简体   繁体   中英

Javascript function isn't recognized

I don't have many knowlege in javascript so I don't know what is the problem here, I create divs dynamically in js and each div call a function when is clicked but the function is not recongized. This is part of the code

for (......) {
  var listatema = document.createElement("div");
  listatema.innerHTML += "<a href='javascript: void(0)' onClick='functest(" + pag + ")'>" + temat + "</a>";
  document.getElementById('menu').appendChild(listatema);}
}

"tema" is a text, the function "functest" has an argument "pag[aux]", this is a number.

The function is:

function functest(arg){
   console.log(arg)
}

other alternative that i tried is change that: onClick='"+ functest(pag) +"' :

i change the position of Quotation marks "" and the function work good but it is executed when the page is loaded, it don't wait to do click.

Your code should work if you're doing something like:

 function functest(arg) { console.log(arg); } for (var i = 0; i < 10; i++) { var listatema = document.createElement("div"); listatema.innerHTML += "<a href='javascript: void(0)' onClick='functest(" + i + ")'>" + i + "</a>"; document.getElementById('menu').appendChild(listatema); }
 <div id="menu"></div>

I would, however, recommend using addEventListener or setting the onClick handler on the document element object rather than setting the innerHTML. Note that setting innerHTML is not advised, especially when rendering user input. See https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations . In your case, it probably isn't really an issue, but it's good practice to avoid it if you can :)

 for (var i = 0; i < 5; i++) { var wrapper = document.createElement("div"); var listatema = document.createElement("a"); listatema.textContent = i; listatema.href = "javascript:void(0)"; listatema.addEventListener('click', function(e) { console.log(this.i); }.bind({ i : i })); wrapper.appendChild(listatema); document.getElementById('menu').appendChild(wrapper); }
 <div id="menu"></div>

onClick='functest(\""+ pag +"\")'

你忘了引用参数。

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