如何在单击子复选框时获取父项的父ID

时间:2013-03-14 05:08:06

标签: javascript jquery asp.net-mvc kendo-ui kendo-treeview

我正在使用带有复选框模板的kendo树视图。

我的HTML代码

<div id="treeview-left" style=" height: 375px; position: absolute;top: 30px;"></div>

我已将树视图定义为:

var treeview1 = $('#treeview-left').kendoTreeView({
            select: onSelect,
            checkboxTemplate: kendo.template($("#treeview-checkbox-template").html()),            
            dragAndDrop: true,
            dataSource: parent, 
            dataTextField: ["parentName", "childName"]
        }).data("kendoTreeView");

复选框模板的定义如下:

<script id="treeview-checkbox-template" type="text/kendo-ui-template">
            <input type="checkbox" />
</script>

数据源将是

var parent = new kendo.data.HierarchicalDataSource({
            type: "POST",
            dataType: "json",
            transport: {
                read: {
                    url: "/Projects/leftdisplay"
                }
            },
            schema: {
                model: {
                    id: "parentid",
                    hasChildren: "childName",
                    children: child
                }
            }
        });

现在父母的孩子会像:

   var child = {
            type: "POST",
            dataType: "json",
            transport: {
                read: {
                    url: function (options) {
                        return kendo.format("/projects/modulesleftdisplay?parentid=" + options.parentid + "&roleid=" + rolevalue + "&projectid=" + projectid + "");
                    }
                }
            },
            schema: {
                model: {
                    id: "childid",
                    hasChildren: function () {
                        return false;
                    }
                }
            }
        };

现在,当我点击子复选框时,我想获得所选孩子的父ID。我怎么能得到它。

我写了像

这样的代码
$("#treeview-left [type=checkbox]").live('change', function (e) {      
    var chkBox = $(this)
    var parentid = chkBox.parent();
    var date = $('#treeview-left').data('kendoTreeView').dataItem(parent_id);
    var parid = date.id;
    var childid = $('#treeview-left').data('kendoTreeView').dataItem(parentid);
});

但是鹦鹉没有得到。如何获取所选子项的父ID。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

试试这个:

// Find all the checkboxes:
var checkboxes = Array.prototype.slice.call(document.querySelectorAll('#yourFormsID input[type=checkbox]'));

checkboxes.forEach(function(checkbox) {                //<== loop through checkboxes
    checkbox.addEventListener('change', function() {   //<== When clicked:
        console.log(this.parentNode.id);               //<== Log the id of the checkbox's parentNode in the console.
    }, false);
});

Here's a demo。务必打开控制台。

答案 1 :(得分:0)

你可以用这个

   var parentId = $(this).parent().closest(parent element).attr('id')

示例:

 var parentId  = $(this).parent().closest('li').attr('id')

而不是

 var chkBox = $(this)

 var parentid = chkBox.parent();

获取父ID。