I have a JavaScript function that is supposed to generate a <div>
dynamically and populate the div using <li></li>
. There is an onclick
event on the <li></li>
tags that calls a function but when clicked, the function does not show. Please help me. The console on my browser shows the following error Uncaught SyntaxError: Unexpected token }
. A sample of my code is below.
function showItem(categoryName) {
cleanDiv();
var alphabet = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
var alphabetArray = [];
alphabetArray = alphabet.split(",");
var stringData = '<div id="alphabet-menu"><h1>' + categoryName + '</h1><ul>';
var letter;
for (var i = 0; i < 26; i++) {
letter = alphabetArray[i];
stringData = stringData + '<li onclick="getData("' + categoryName + '","' + letter + '");">' + letter + '</li>';
}
stringData = stringData + '</ul></div><div id="list-menu"><input type="button" onclick="animateRight();" value="Back"></input>' + '<div id="home-button" onclick="animateRight();"><img src="img/home.png"></div></div>';
document.getElementById("content").innerHTML = '' + stringData + '';
}
function getData(category, letter) {
alert(category + letter);
}
change your code as below
letter = alphabetArray[i];
stringData = stringData+'<li onclick="getData(\''+categoryName+'\',\''+letter+'\');">'+letter+'</li>';
There is a syntax error in getData
declaration. Here's a working fiddle: http://jsfiddle.net/CfRBc/
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.