我有一個附加到jQuery點擊事件的代碼塊。這裏的元素:jQuery點擊事件不附加到淘汰賽模板
<!-- Profiles -->
<div class="profiles">
<h1>Profiles</h1>
<div class="profile">
<div class="name">
<input type="text" maxlength="14" value="Default" />
<span class="rename">q</span>
</div>
<div class="controls">
<span class="edit">EDIT</span>
<span class="duplicate">COPY</span>
<span class="delete default">J</span>
<div class="alert-box">
<p>Are you sure you want to delete this profile?</p>
<div>Y</div>
<div>N</div>
</div>
</div>
<div class="saved">
<span class="cancel-button">Cancel</span><span class="save-button">Save</span>
</div>
</div>
</div>
當該項目被選中時,它可用於編輯。這裏的事件偵聽器:
$('.rename').click(function() {
$('.selected .rename').fadeIn(80);
$(this).fadeOut(80);
$(this).parent().addClass('selected');
});
有監聽點擊頁面上的任何位置,以取消該項目正在編輯另一個事件:
$(document).click(function() {
$(".selected .rename").fadeIn(80);
$('.name').removeClass('selected');
});
當它被點擊,就應選擇允許編輯。當我將代碼從profile
移到淘汰賽模板中時,它不再監聽點擊事件。當我在Chrome工具中檢查事件監聽器時,聽衆無處可尋。以下是我的模板:
<div class="profiles">
<h1>Profiles</h1>
<div data-bind="template: { name: 'profilestempl', foreach: $root.profiles }"></div>
</div>
<script type="text/html" id="profilestempl">
<div class="profile">
<div class="name">
<input type="text" maxlength="14" data-bind="value: name" />
<span class="rename">q</span>
</div>
<div class="controls">
<span class="edit">EDIT</span>
<span class="duplicate">COPY</span>
<span class="delete">J</span>
<div class="alert-box">
<p>Are you sure you want to delete this profile?</p>
<div>N</div><div>Y</div>
</div>
</div>
<div class="saved">
<span class="cancel-button">Cancel</span><span class="save-button">Save</span>
</div>
</div>
</script>
有人可以向我解釋爲什麼事件偵聽器不再適用於動態添加的元素嗎?我也想幫助解決這個問題。謝謝!
這解決了問題,謝謝! – ijb109