簡體   English   中英

如何在子進程排序時獲取父ID

[英]How to get the parent id when the child is sort

這個問題與此有關: 如何在排序后顯示父級的新順序?

我已經解決了上面的問題。 現在我想在孩子排序時獲得父ID。

示例:當我將水交換到電力時,

         <li id="1">
            <span class="cat-title">Utilities</span>
            <ul class="dropenv mt">
                <li class="innerList">Electricity</li>
                <li class="innerList">Water</li>
                <li class="innerList">Trash</li>
                <li class="innerList">Television</li>
            </ul>
         </li>

輸出必須是,

   1_Electricity
   1_Water
   1_Trash
   1_Television

因為1是Utilities的id

以下是代碼:

 [.............]
        var parentID;
        var origColor;
        $(".dropenv").sortable({
            connectWith: "ul.env-data",
            dropOnEmpty: true,
            start: function(event, ui) {
                origColor = ui.item.text();

                //this is the id that produce undefined value
                parentID = ui.item.parent().siblings('li').attr('id');
            },
            stop: function(event, ui) {
                var order = [];

                ui.item.closest('ul').children('li').each(function() {
                    order.push($(this).data('position'));
                    var c = $(this).text();
                    var z = parentID;
                    //if (c === origColor) {
                    //    var z = origTitle;
                    //} else {
                    //    var z = $(this).parent().siblings('.cat-title').text();
                    //}
                    $("#cl").append(z + "_" + c + "<br /\>");
                });
            }
        });

[.............]

以上代碼產生未定義的值:

   undefined_Electricity
   undefined_Water
   undefined_Trash
   undefined_Television

如何獲得確切的父ID?

嘗試

parentID = ui.item.closest('li[id]').attr('id');

另一個完整的解決

$("#sortable").sortable({
    connectWith: "ul.env-data",
    dropOnEmpty: true,
    stop: function(event, ui) {
        var parentId = ui.item.parent().closest('li').attr('id');
        // Or this
        //var parentId = ui.item.closest('li[id]').attr('id');
        ui.item.closest('ul').children('li').each(function() {
            var $this = $(this);
            var text = $this.data('text');
            if(!text){
                text = $this.text();
                $this.data('text', text);
            }
            $this.text(parentId + '_' + text)
        });
    }
});

演示: 小提琴

你的項目是<ul class="dropenv mt"> ..轉到parent(li)並獲取id ..不需要sibling() ;

嘗試這個

var parentID ="";
parentID = ui.item.parent('li').attr('id');

使用默認值初始化parentID。 var parentID ='';

然后搜索父母。

 parentID = ui.item.parent().parent('li').attr('id');

暫無
暫無

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

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