getting undefined error in javascript
I am trying to list all categories in my XML file and link them with a javascript function which opens an xsl file.
I'keep getting this error: Novel is Undefined. where N开发者_运维问答ovel is a category from the XML
Here is my code.
var root=myxmldoc.getElementsByTagName("CATEGORY");
for (i=0;i<root.length;++i) {
var catName=(root[i].childNodes[0].nodeValue);
txt='<a href="#" onClick="javascript:Navigate('+catName+')">'+catName+'</a>';
document.getElementById("left-sidebar").innerHTML+=txt;
}
In the code above, Navigate(var) is a function that loads various .XSL files for each category.
Please can anyone help me understand why the error keeps coming up?
Thanks
When you generate the link, it'll come up as:
<a href="#" onClick="javascript:Navigate(Novel)">Novel</a>
Note the lack of quotes around Novel
, meaning Javascript will see that as a variable, which happens to not be defined.
You neeed to embed quotes in your string generation like this:
txt='<a href="#" onClick="javascript:Navigate(\''+catName+'\')">'+catName+'</a>';
^^ here ^^ and here
so that the HTML will look like:
<a href="#" onClick="javascript:Navigate('Novel')">Novel</a>
精彩评论