簡體   English   中英

jQuery最近()+查找()樹遍歷

[英]JQuery closest() + find() tree traversal

給定這樣的結構:

<div class="portlet">
    <div class="portlet-config">
        <p>Some configuration</p>
    </div>
    <div class="portlet-header">Configurable portlet</div>
    <div class="portlet-content">This has a configuration window. Click on pencil icon to open.</div>
</div>

首先,我將這些DIV附加到portlet-header(以顯示一些按鈕)

<div class="portlet-button-container">
    <div class="portlet-button portlet-btn-delete ui-icon ui-icon-close"></div>
    <div class="portlet-button portlet-btn-toggle ui-icon ui-icon-minusthick"></div>
    <div class="portlet-button portlet-btn-config ui-icon ui-icon-pencil"></div>
</div>

然后我將jquery-ui dialog()插件應用於portlet-config DIV

$(".portlet-config").dialog({
    autoOpen: false,
    show: {
        effect: "fade",
        duration: 200
    },
    hide: {
        effect: "fade",
        duration: 500
    },
    modal: true,
    buttons: {
        Ok: function () {
            $(this).dialog("close");
        }
    }
});

然后我添加了點擊處理程序

$(".portlet-btn-toggle").click(function () {
    var icon = $(this);
    icon.toggleClass("ui-icon-minusthick ui-icon-plusthick");
    icon.closest(".portlet").find(".portlet-content").toggle();
});

$(".portlet-btn-delete").click(function () {
    var icon = $(this);
    icon.closest(".portlet").hide();
});

$(".portlet-btn-config").click(function () {
    var icon = $(this);
    icon.closest(".portlet").find(".portlet-config").dialog("open");
});

當用戶單擊鉛筆時,似乎找不到portlet-config DIV。

更確切地說,似乎:

$(this)                                             // OK, returns an object
$(this).closest(".portlet")                         // OK, returns an object
$(this).closest(".portlet").find(".portlet-config") // NOK, returns null

這是重現此問題的小提琴: http : //jsfiddle.net/silenzioso/M6LmS/

提前致謝

您對$(".portlet-config").dialog調用比您預期的要多。 如果查看DOM,則可以看到div已移出其原始位置並添加到文檔的末尾。 大概是為了覆蓋對話框效果。

您可以考慮在對話框div上放置一個唯一的ID,以便再次找到它。 也許您可以使用數據屬性將關聯的對話框div ID存儲在按鈕中。

<div class="portlet">
    <div class="portlet-config" id="dialog1">
        <p>Some configuration</p>
    </div>
    <div class='portlet-button' data-config="dialog1"></div>
</div>

...

var id = $(this).data('config');
var config = $('#'+id);

如果要在jQuery中動態創建新的DOM元素,請確保在正文或文檔或從第一頁顯示中定義的其他元素上添加事件單擊(我的意思是服務器響應):

$('body').on('click', '.portlet-btn-config', function(e){

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM