随着jQuery的事件代表团(http://learn.jquery.com/events/event-delegation),我能够有自动连接到其被添加到UL LI元素的事件,如在后续代码:如何将一个类自动应用于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>
.clone(true,true)复制数据(样式,属性等)和事件。 – Virus721
事件处理程序不会自动绑定到添加的元素。相反,单个处理程序绑定到祖先元素(或“文档”本身),并且该事件将从添加的元素直到祖先。没有这样的机制来动态地暴露类和样式。 –