尝试创建动态JQUERY元素以添加到HTML页面。想要点击一个事件,从一个数组创建元素,然后新元素转到不同的功能。到目前为止,我已经:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
<title>Adding buttons dynamically to JQuery </title>
<link type = "text/css" rel="stylesheet" href="jquery-ui.css">
<script type = "text/javascript" src="jquery.min.js"></script>
<script type = "text/javascript" src="jquery-ui.min.js"></script>
</head>
<body>
<p>Firing off without a hitch, HTML page loaded properly</p>
<button id="classChoice">Show Classes</button>
<div id='classSection' style="margin:50px">This is our new section test
area</div>
<script type="text/javascript">
//Classes Array
var classesArray = [ 'Spanish','English','French'];
var classIndex = 0;
//Button functionality
var btn = document.getElementById('classChoice');
btn.addEventListener("click",click2Handler,false);
//Button handler
function click2Handler(){
alert('clicked button!'); /*Code to create variable for new button */
evaluator();
}
//Evaluator function
function evaluator()
{
if(classIndex<classesArray.length)
{//Only operate to the length of the classes array
for(var i = 0; i< classesArray.length;i++)
{
var whereCreated = jQuery('#classSection');//where to add
var id = 'btn' + classesArray[classIndex];
whereCreated.append('<br><button id="' + id + '">' + classesArray[classIndex] + '</button>');
jQuery('#'+id).button().click(function(){
alert('Dynamically added button: '+ id + ' has been clicked...going to selector function');alert('id of button clicked: ' + id);
selector(id);
});
console.log('whereCreated: '+whereCreated+". id: " +id);
classIndex++;
}
console.log('classIndex: ' + classIndex);
}
}
function selector(btnSelection)
{
switch(btnSelection)
{
case 'btnSpanish':
alert('Buenos Dias!'); break;
case 'btnEnglish':
alert('Howdy Partner!');break;
case 'btnFrench':
alert('Oui oui monsieur!');break;
default : alert('Unhandled exception inside selection');
break;
}
}
</script>
</body>
</html>
问题是只有创建的最后一个按钮在选择器函数内部进行了id评估,在本例中为btnFrench。如何让每个按钮传递正确的ID?
答案 0 :(得分:2)
您可以创建closure:
(function (id) {
jQuery('#' + id).button().click(function () {
alert('Dynamically added button: ' + id + ' has been clicked...going to selector function');
alert('id of button clicked: ' + id);
selector(id);
});
})(id);
闭包定义了一个新范围。这是必要的,因为你的 在循环结束之后才调用handler,所以我不是 调用时的范围的一部分,或者(在某些情况下)具有的范围 循环中的最后一个可能值。 (src)