How to force a javascript function to treat a parameter as string? -
<script> var id = "432.000+444"; myfunc(id); document.write("<a onclick=\"myfunc("+id+");\" href=#>click me</a><br>"); function myfunc(id) { alert(id); } </script>
myfunc(id) prints string normally, clicking on element prints 876 (treats number , adds 432 , 444). how can prevent this? want treated string.
put in quotes:
document.write("<a onclick=\"myfunc('"+id+"');\" href=#>click me</a><br>"); // ---------------------------------^------^
fwiw, advise not using onxyz
-attribute-style event handlers. 1 thing, functions call them have globals, not thing. instead, use modern event handling (addeventlistener
, or attachevent
on old ie; here's function handles issue) or @ least onclick
property.
var id = "432.000+444"; var link = document.createelement("a"); link.onclick = myfunc.bind(link, id); link.href = "#"; link.appendtextnode("click me"); appropriateparentelement.appendchild(link); appropriateparentelement.appendchild(document.createelement("br")); function myfunc(id) { alert(id); }
Comments
Post a Comment