使用 jQuery 的事件委托 ( http://learn.jquery.com/events/event-delegation ),我可以将事件自动附加到添加到 UL 的 LI 元素上,如下面的代码所示:
但是我如何自动添加样式呢?
<html>
<head>
<title>test</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function() {
$("ul#list").append('<li>added before</li>');
//assures that any new LI added to LIST will have this click event
$("ul#list").on("click","li", function() {
$(this).addClass("selected");
});
//how to also assure that any LI added to LIST will have this style
$("ul#list li").addClass("original");
$("ul#list").append('<li>added after</li>');
});
</script>
<style type="text/css">
li.original {
color: red;
cursor: pointer;
}
li.selected {
color:green;
}
</style>
</head>
<body>
<div id="container">
<ul id="list">
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
</div>
</body>