[英]Hide a specific DIV element that has been dynamically generated
字段Description
是可選的,只有在用戶單擊+ Description
按鈕時才會出現。 但是,當生成另一個 div 時,代碼失去了它應該隱藏的元素的焦點,並且按鈕不再起作用。
<script>
$(document).ready(function(e){
$(document).on('click', '#hide-desc', function(e) {
$("#description").slideToggle();
});
});
</script>
我有一個按鈕可以刪除和添加以下 div:
<div class="item-wrapper">
<div class="item-inner-wrapper">
<!-- Among other stuff -->
<div id="description" class="item-child-desc">
{{ form }}
</div>
</div>
<div class="item-action-button">
<!-- Deletes item-wrapper and another button adds it -->
<a id="delete" href="#" class="button alt small special">Remove</a>
<a id="hide-desc" class="button alt small">+ Description</a>
</div>
</div>
我知道該函數必須能夠識別我正在談論的description
,但我不知道如何做到這一點。 我試圖獲取按鈕的父 div 並使用find()
方法指定 div,但我無法使其工作。
我在使用自動完成功能時遇到了同樣的問題。 我相信如果我能弄清楚我必須做什么,我會讓兩者都工作。
我不完全確定這個問題,但如果我的理解是正確的,我相信我可能已經為您找到了解決方案。 使用jQuery Event Delegation ,比較簡單!
運行此代碼片段,看看我是否接近解決方案:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="item-action-button"> <a href="#" class="delete button alt small special">Remove</a> <a class="hide-desc button alt small">+ Description</a> <div class="item-child-desc">{{ form }}</div> </div> <div class="item-action-button"> <a href="#" class="delete button alt small special">Remove</a> <a class="hide-desc button alt small">+ Description</a> </div> <div class="item-action-button"> <a href="#" class="delete button alt small special">Remove</a> <a class="hide-desc button alt small">+ Description</a> <div class="item-child-desc">{{ form }}</div> </div> <div class="item-action-button"> <a href="#" class="delete button alt small special">Remove</a> <a class="hide-desc button alt small">+ Description</a> </div> <script> $(document).ready(function (e) { $(".item-action-button").on('click', '.hide-desc', function (e) { $(e.delegateTarget).find(".item-child-desc").slideToggle(); }); }); </script> <style> .item-child-desc { display: none; } </style>
使用 id 進行事件處理的問題在於它們只注冊到具有匹配 id的最后一個元素。 如果您想要為特定類型的所有元素使用一個事件處理程序,請使用特定類或標記的元素注冊一個事件處理程序。 否則你會傷害自己。 希望這可以幫助!
根據您的評論,我假設您的 html 看起來像這樣(請注意,我們使用.description
而不是#description
因為它們不是唯一元素):
<div class="item-wrapper">
<div class="item-action-button">
<a id="delete" href="#" class="button alt small special">Remove</a>
<a id="hide-desc" class="button alt small">+ Description</a>
</div>
<div class="description" class="item-child-desc">
blergh
</div>
</div>
我們只需要使用e.target
來查找父.item-wrapper
以引用事件源,然后搜索子.description
:
$(e.target).parents(".item-wrapper").find(".description").slideToggle();
根據您添加的示例 html,以下內容也無需修改即可使用:
$(e.target).parents(".item-wrapper").find(".item-child-desc").slideToggle();
也可以只使用this
:
$(this).parents(".item-wrapper").find(".item-child-desc").slideToggle();
在所有情況下,關鍵部分是parents(".item-wrapper")
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.