当我单击动态添加的项目时,我正在尝试更改 css 类。我确实在 doStuffWithThisItem 方法中有该项目,但似乎更改没有保存回 dom 树。但我无法让它工作。你能发现我做错了什么吗?
<style type="text/css">
.selectedItem {
background-color: red;
}
</style>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function () {
function doStuffWithThisItem(item) {
alert(item.id);
jQuery(item.id).addClass('selectedItem');
}
function parseNodes(nodes, level) {
var ol = document.createElement("ul");
for (var i = 0; i < nodes.length; i++) {
ol.appendChild(parseChildNode(nodes[i], level));
}
return ol;
}
function parseChildNode(child, level) {
var li = document.createElement('li');
jQuery(li).html(child.title)
.attr("id", child.id)
.click(function () {
if (level == 1) {
doStuffWithThisItem(this);
}
});
return li;
}
window.jsonData = [{
"title": "Item 1",
"id": "item1",
"description": "Item 1 description"
},
{
"title": "Item 2",
"id": "item2",
"description": "item 2 description"
}];
jQuery("#someDiv").html(parseNodes(jsonData, 1));
});
</script>
<div id="someDiv"></div>