将 Id 传递给 Onclick 函数 JQGrid

Pass Id to a Onclick Function JQGrid

我有一个 JQGrid.I 需要将一些 Id 带到 OnClick function.In 我的场景我想获得 BasicId 到 OnClick 函数。

我的代码

 function grid() {
    //JqGrid
    $('#griddata').html('<table class="table" id="jqgrid"></table>')
    $('#jqgrid').jqGrid({

        url: '/Admin/GetBasicData/',

        datatype: 'json',
        mtype: 'GET',
        //columns names
        colNames: ['BasicId','Images'],
        //columns model
        colModel: [

                    { name: 'BasicId', index: 'BasicId', resizable: false },


                     {
                         name: 'Images',
                         width: 120,

                         formatter: function () {
                             return "<button class='btn btn-warning btn-xs' onclick='OpenDialog()' style='margin-left:30%'>View</button>";
                         }
                     },

//Some Code here

打开对话框功能

function OpenDialog(BasicId)
{
//Some code here
}

在你的按钮中写js事件html不是一个好主意,它违反了'un-obtrusive javasript'原则。您可以改为在 render 函数中对整个网格添加点击事件,并在回调中根据按钮是否被点击进行过滤。

//不清楚jqgrid的语法,但大致是:

render: function(){
    $('#jqgrid').unbind('click').on('click', function(){
        if($(e.target).hasClass('btn-warning')){
            var tr = $(e.target).parent('tr');
            //retrieve the basicId from 'tr'
            OpenDialog(/*pass the basicId*/)
        }
    })
}

您可以使用 onclick='OpenDialog.call(this, event)' 而不是 onclick='OpenDialog()'。您将 OpenDialog 内部的 this 初始化为单击的 <button>event.target。因此您的代码可能如下所示

function OpenDialog (e) {
    var rowid = $(this).closest("tr.jqgrow").attr("id"),
        $grid = $(this).closest(".ui-jqgrid-btable"),
        basicId = $grid.jqGrid("getCell", rowid, "BasicId");

    // ...

    e.stopPropagation();
}

多一个选项就更好了:您不需要指定任何 onclick。取而代之的是,您可以使用 jqGrid 的 beforeSelectRow callback

beforeSelectRow (rowid, e) {
    var $td = $(e.target).closest("td"),
        iCol = $.jgrid.getCellIndex($td[0]),
        colModel = $(this).jqGrid("getGridParam", "colModel"),
        basicId = $(this).jqGrid("getCell", rowid, "BasicId");
    if (colModel[iCol].name === "Images") { // click in the column "Images"
        // one can make additional test for 
        //   if (e.target.nodeName.toUpperCase() === "button")
        // to be sure that it was click to the button
        // and not the click on another part of the column
        OpenDialog(rowid);
        return false; // don't select the row - optional
    }
}

最后一种方式的主要优点:不需要再做任何额外的绑定(每次绑定都获取内存资源,需要时间)。网格中已经存在 click 个处理程序,可以使用它。由于事件冒泡,只需一个单击处理程序就足够了。 e.target 为我们提供了关于被点击元素的完整信息。