隨着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
事件處理程序不會自動綁定到添加的元素。相反,單個處理程序綁定到祖先元素(或「文檔」本身),並且該事件將從添加的元素直到祖先。沒有這樣的機制來動態地暴露類和樣式。 –