我的新demo 演示了如何做到这一点:
在演示中,我使用了 jqGrid 插件目录中包含的jquery.contextmenu.js 中的small modification。我的代码远非完美,尤其是在 CSS 类的使用和在contextMenu 的menuStyle 和itemHoverStyle 中使用的颜色方面。尽管如此,我们确实需要代码。
演示的主要部分由createContexMenuFromNavigatorButtons 函数组成,该函数可以在构建导航栏后调用(在navGrid 和navButtonAdd 之后)。用法很简单:
createContexMenuFromNavigatorButtons($("#list"), '#pager');
createContexMenuFromNavigatorButtons的代码如下:
function createContexMenuFromNavigatorButtons(grid, pager) {
var buttons = $('table.navtable .ui-pg-button', pager),
myBinding = {},
menuId = 'menu_' + grid[0].id,
menuDiv = $('<div>').attr('id', menuId).hide(),
menuUl = $('<ul>');
menuUl.appendTo(menuDiv);
buttons.each(function () {
var $div = $(this).children('div.ui-pg-div:first'), $spanIcon, text, $td, id, $li, gridId = grid[0].id;
if ($div.length === 1) {
text = $div.text();
$td = $div.parent();
if (text === '') {
text = $td.attr('title');
}
if (this.id !== '' && text !== '') {
id = 'menuitem_' + this.id;
if (id.length > gridId.length + 2) {
id = id.substr(0, id.length - gridId.length - 1);
}
} else {
// for custom buttons
id = $.jgrid.randId();
}
$li = $('<li>').attr('id', id);
$spanIcon = $div.children('span.ui-icon');
$li.append($spanIcon.clone().css("float", "left"));
$li.append($('<span>').css({
'font-size': '11px',
'font-family': 'Verdana',
'margin-left': '0.5em'
}).text(text));
menuUl.append($li);
myBinding[id] = (function ($button) {
return function () { $button.click(); };
}($div));
}
});
menuDiv.appendTo('body');
grid.contextMenu(menuId, {
bindings: myBinding,
onContextMenu: function (e) {
var rowId = $(e.target).closest("tr.jqgrow").attr("id"), p = grid[0].p, i, lastSelId;
if (rowId) {
i = $.inArray(rowId, p.selarrrow);
if (p.selrow !== rowId && i < 0) {
// prevent the row from be unselected
// the implementation is for "multiselect:false" which we use,
// but one can easy modify the code for "multiselect:true"
grid.jqGrid('setSelection', rowId);
} else if (p.multiselect) {
// Edit will edit FIRST selected row.
// rowId is allready selected, but can be not the last selected.
// Se we swap rowId with the first element of the array p.selarrrow
lastSelId = p.selarrrow[p.selarrrow.length - 1];
if (i !== p.selarrrow.length - 1) {
p.selarrrow[p.selarrrow.length - 1] = rowId;
p.selarrrow[i] = lastSelId;
p.selrow = rowId;
}
}
return true;
} else {
return false; // no contex menu
}
},
menuStyle: {
backgroundColor: '#fcfdfd',
border: '1px solid #a6c9e2',
maxWidth: '600px',
width: '100%'
},
itemHoverStyle: {
border: '1px solid #79b7e7',
color: '#1d5987',
backgroundColor: '#d0e5f5'
}
});
}