您好我想创建动态多个jqgrid。但是创建一个jqgrid fisrt动态这个下来的HTML
<div dir='rtl' align='center' class='table - responsive'><div class='row well'>
<table id='dataArray' cellpadding='0' cellspacing='0'></table>
<div id="pager_dataArray"></div>
</div>
</div>
<br />
<div dir='rtl' align='center' class='table - responsive'>
<div class='row well'>
<table id='dataArray2' cellpadding='0' cellspacing='0'></table>
<div id="pager_dataArray2"></div>
</div>
</div>
然后使用js代码创建jqgrid;请注意iam在js文件中获取模型和标题网格调用函数,
LoadGrid()
数据:LoadGrid(), colNames:getColNames(LoadGrid()[0]), colModel:getColModels(LoadGrid()[0]),
var searchOptions = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'bw', 'bn', 'in', 'ni', 'ew', 'en', 'cn', 'nc'];
$(document).ready(function () {
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var today = d.getFullYear() + '/' +
(('' + month).length < 2 ? '0' : '') + month + '/' +
(('' + day).length < 2 ? '0' : '') + day;
$("#dynamicGrouping").change(function () {
var groupingName = $(this).val();
alert(groupingName)
if (groupingName) {
//$('#list').jqGrid('groupingGroupBy', ['AddDate_D', 'Name_c']);
$('#' + gridid).jqGrid('groupingGroupBy', [groupingName]);
} else {
$('#' + gridid).jqGrid('groupingRemove');
}
});
caption: "تست گرید",
$('#' + gridid).jqGrid({
caption: "تست گرید",
//url from wich data should be requested
// url: '@Url.Action("GetProducts","Home")',
datatype: 'local',
//این تابع از فایل androidfunction فراخوانی می شود
data: LoadGrid(),
colNames: getColNames(LoadGrid()[0]),
colModel: getColModels(LoadGrid()[0]),
jsonReader: {
root: "Rows",
page: "Page",
total: "Total",
records: "Records",
repeatitems: true,
userdata: "UserData",
id: "Id",
cell: "RowCells"
},
grouping: true,
iconSet: "glyphIcon",
groupingView: {
// groupField: ['AddDate_D' , 'Name_c'],
groupColumnShow: [true],
groupText: ['<b>{0}</b>'],
groupCollapse: true,
groupOrder: ['asc'],
groupSummary: [true]
},
cmTemplate: { editable: false, autoResizable: true },
toppager: true,
// groupingView: { groupField: ['AddDate_D'] },
mtype: 'POST',
footerrow: true,
// userDataOnFooter : true,
//gridComplete: function () {
// var $grid = $("#FooTable");
// var colSum = $grid.jqGrid('getCol', 'Price_Num', false, 'sum');
// $grid.jqGrid('footerData', 'set', { price: colSum });
//},
pager: $('#' + pagegrid),
//number of rows per page
rowNum: 10,
rowList: [10, 20, 50, 100],
//initial sorting column
sortname: 'Id',
//initial sorting direction
sortorder: 'asc',
// loadonce: true,
shrinkToFit: true,
//we want to display total records count
viewrecords: true,
width: 'auto',
height: 'auto',
hidegrid: false,
direction: "rtl",
gridview: true,
altRows: true,
rownumbers: true,
autoencode: true,
treeGrid: true,
treeGridModel: 'adjacency',
ExpandColClick: true,
// ignoreCase: true,
//loadComplete : function() {
// var table = this;
// setTimeout(function(){
// updatePagerIcons(table);
// }, 0);
//},
loadComplete: function () {
sumarValores($(this))
},
loadError: function (xhr, st, err) {
jQuery("#rsperror").html("Type: " + st + "; Response: " + xhr.status + " " + xhr.statusText);
},
})
.navGrid(
$('#' + pagegrid),
//enabling buttons
{ add: false, del: false, edit: false, search: false },
//edit option
{
width: 'auto', checkOnUpdate: true, checkOnSubmit: true,
beforeShowForm: function (form) {
centerDialog(form, $('#' + gridid));
}
},
//add options
{
width: 'auto', url: '@Url.Action("AddProduct","Home")',
},
//add options
//delete options
{
url: '@Url.Action("DeleteProduct","Home")', reloadAfterSubmit: false
})
.jqGrid('inlineNav', $('#' + pagegrid),
{
// cloneToTop: true,
edit: false, add: true, save: false, cancel: false,
edittext: "ویرایش", addtext: "جدید", savetext: "ذخیره", canceltext: "لغو",
addParams: {
// اگر میخواهید ردیفهای جدید در ابتدا ظاهر شوند، این سطر را حذف کنید
position: "first", //ردیفهای جدید در آخر ظاهر میشوند
rowID: '_empty',
useDefValues: true,
addRowParams: getInlineNavParams(true)
},
editParams: getInlineNavParams(false)
}
)
$('#' + gridid).jqGrid('navButtonAdd', '#list_toppager',
{
caption: ""/*"Show"*/, buttonicon: "ui-icon-extlink", title: "Show Link",
onClickButton: function () {
var grid = $('#' + gridid);
var rowid = grid.jqGrid('getGridParam', 'selrow');
window.location = grid.jqGrid('getCell', rowid, 'dataUrl');
}
});
$('#' + gridid).jqGrid('filterToolbar', {
stringResult: true,//// وجود این سطر سبب میشود تا اپراتورها به سرور ارسال شوند
enableClear: false,
searchOnEnter: true,
searchOperators: true, // فعال سازی منوی اپراتورها
defaultSearch: "cn"
});
function getSelectedRow() {
var grid = $('#' + gridid);
var rowKey = grid.jqGrid('getGridParam', "selrow");
if (rowKey)
alert("Selected row primary key is: " + rowKey);
else
alert("No rows are selected");
}
});
function sumarValores($self) {
var sumaHa = 0;
var columnNames = $('#' + gridid).jqGrid('getGridParam', 'colNames');
var global;
var footer = {};
for (var z = 0; z < columnNames.length; z++) {
var colN = columnNames[z];
// $self.jqGrid("footerData", "set", footer);
if (colN == "Price") {
colN = colN.concat('_Num');
var sumtotal = $self.jqGrid("getCol", colN, false, "sum");
// global = colN;
global = 'Price_Num';
footer[global] = sumtotal;
//$self.jqGrid("footerData", "set", {
// Price_Num: sumtotal,
//});
$self.jqGrid("footerData", "set", footer);
break;
}
if (colN == "AddDate") {
global = 'AddDate_D';
var sumtotald = $self.jqGrid("getCol", colN, false, "sum");
// footer[global] = sumtotald;
$self.jqGrid("footerData", "set",
{
AddDate_D: sumtotald,
}
);
}
}
}
function getInlineNavParams(isAdd) {
return {
// استفاده از آدرسهای مختلف برای حالات ویرایش و ثبت اطلاعات جدید
url: isAdd ? '@Url.Action("AddUser", "Home")' : '@Url.Action("EditUser","Home")',
key: true,
restoreAfterError: false, // این مورد سبب میشود تا اعتبارسنجی سمت سرور قابل اعمال شود
oneditfunc: function (rowId) {
// نمایش دکمههای ذخیره و لغو داخل همان سطر
$("#jSaveButton_" + rowId).show();
$("#jCancelButton_" + rowId).show();
},
successfunc: function () {
var $self = $(this);
setTimeout(function () {
$self.trigger("reloadGrid"); // دریافت کلید اصلی ردیف از سرور
}, 50);
},
errorfunc: function (rowid, response, stat) {
if (stat != 'error') // this.Response.StatusCode == 200
return;
var result = $.parseJSON(response.responseText);
if (result.success === false) {
//نمایش خطای اعتبار سنجی سمت سرور پس از ویرایش یا افزودن
$.jgrid.info_dialog($.jgrid.errors.errcap,
'<div class="ui-state-error">' + result.message + '</div>',
$.jgrid.edit.bClose,
{ buttonalign: 'center' });
}
}
};
}
function centerDialog(form, grid) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
}
function getColNames(data, status) {
var keys = [];
if (status != 'headr') {
for (var key in data) {
if (data.hasOwnProperty(key)) {
keys.push((key.split('_'))[0]);
}
}
keys.push('');
}
else {
for (var key in data) {
if (data.hasOwnProperty(key)) {
keys.push(key);
}
}
keys.push('');
}
return keys;
}
function getColModels(data) {
var colNames = getColNames(data, 'headr');
var colModelsArray = [];
for (var i = 0; i < colNames.length; i++) {
var str;
if (i === 0) {
str = {
name: (colNames[i]),
index: (colNames[i]),
key: true,
editable: false,
search: false,
width: 20,
};
} else if (i >= 1 && i <= colNames.length - 2) {
switch ((colNames[i].split('_'))[1]) {
case ('Num'):
str = {
name: (colNames[i]),
index: (colNames[i]),
editable: true,
summaryType: 'sum', summaryTpl: '<b>جمع مشاهدات: {0}</b>',
//width: 100,
searchoptions: { sopt: searchOptions },
formatter: 'currency',
formatoptions:
{
decimalSeparator: '.',
thousandsSeparator: ',',
decimalPlaces: 0,
prefix: 'ريال'
},
editable: true, edittype: 'text',
// summaryType: function (val, name, record) {
};
// tt = 'Price_Num';
break;
case ('D'):
str = {
name: (colNames[i]),
index: (colNames[i]),
editable: true,
// width: 100,
searchoptions: {
dataInit: function (elem) {
$(elem).datepicker({
dateFormat: 'm/d/y',
onClose: function (event) {
$('#' + gridid).trigger("reloadGrid", [{ page: 1 }]);
}
});
// datepicker({
// dateFormat: 'dd/mm/yy',
// changeYear: true,
// changeMonth: true,
// showWeek: true,
// onSelect: function (dateText, inst) {
// setTimeout(function () {
// $('#' + gridid)[0].triggerToolbar();
// }, 100);
// }
//});
},
dataInit: function (elem) {
$(elem).datepicker({
dateFormat: 'm/d/y',
onClose: function (event) {
$('#' + gridid).trigger("reloadGrid", [{ page: 2 }]);
}
});
}
, sopt: searchOptions
},
editoptions: {
maxlength: 10,
onclick: 'PersianDatePicker.Show(this,' + '1395/02/01' + ')'
},
editrules: {
required: true
}
};
break;
case ('c'):
str = {
name: (colNames[i]),
index: (colNames[i]),
editable: true,
//width:100,
searchoptions: { sopt: searchOptions },
};
break;
default:
// alert('>41');
}
}
else {
str = {
name: 'myac',
index: colNames[i],
resize: false,
fixed: true, sortable: false,
formatter: 'actions',
search: false,
formatoptions: {
keys: true
},
}
}
//formatter: 'currency',
//formatoptions:
//{
// decimalSeparator: '.',
// thousandsSeparator: ',',
// decimalPlaces: 2,
// prefix: '$'
//},
//editable: true, edittype: 'text',
colModelsArray.push(str);
}
return colModelsArray;
}
function updatePagerIcons(table) {
//var replacement =
//{
// 'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
// 'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
// 'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
// 'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
//};
//$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
// var icon = $(this);
// var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
// if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
//})
}
&#13;
$(document).ready(function () {
function LoadGrid() {
object = {
"dataArray":
[
{ id_R: 1, Name_c: "dummy1", AddDate_D: "1394/07/27", Price_Num: "10000" },
{ id_R: 2, Name_c: "dummy2", AddDate_D: "1394/07/28", Price_Num: "120000" },
],
"dataArray2":
[
{ id_R: 9, Name2_c: "dummy9", AddDate2_D: "1393/04/28", Price2_Num: "200000" },
{ id_R: 10, Name_c: "dummy10", AddDate_D: "1393/04/04", Price_Num: "2100000" },
]
};
// برای مپ کردن ارایه یه ارایه دیگر
//departement = $.map(dataArray, function (value, index) {
// return [value];
//});
var names = Object.getOwnPropertyNames(object);
// var names = 'grd1'
var col = [];
var gridarr = [];
var pagegrarr = [];
//مقادیر ارایه را در متغیر زیر می ریزد
var col = Object.values(object);
//تعداد ارایه برای گرید بدست اوردیم
var countarr = col.length;
for (var i = 0; i < countarr; i++) {
//اسم جدول گرید
gridarr[i] = names[i];
pagegrarr[i] = 'pager_' + names[i];
// return col[i];
}
flag++;
switch (flag) {
case 1:
case 2:
case 3:
case 4:
gridid = gridarr[0]
pagegrid = pagegrarr[0]
return col[0];
break;
case 5:
case 6:
case 7:
case 8:
gridid = gridarr[1]
pagegrid = pagegrarr[1]
return col[1];
break;
default:
break;
}
}
});
答案 0 :(得分:0)
这个答案:
<script>
$(document).ready(function () {
function grid(tt) {
//=== LOCA VARIABLES ===//$.jgrid.randId()
var myGrid = $("<table>").attr("id", tt);
var myPager = $("<div>").attr("id", tt +"_pager");
var localData1 = {
"page": 1,
"totalRecords": 5,
"pageSize": 3,
"rows": [
{ Name: "Name 1" },
{ Name: "Name 3" },
{ Name: "Name 2" }
]
};
function publicInit() {
$("body").append(myGrid, myPager);
myGrid.jqGrid({
pager: myPager,
data: localData1.rows,
datatype: "local",
colModel: [
{ name: 'Name', index: 'Name', width: "500" }
],
//localReader: {
// repeatitems: false
// },
// rowNum: 3,
viewrecords: true,
height: "auto",
ignoreCase: true
});
}
//=== REVEALING PATTERN===//
return {
init: publicInit
}
};
var grid1 = new grid("y");
grid1.init();
$("body").append("<br><br>"); //Add some spacing to distinguish between both grids
var grid2 = new grid("c");
grid2.init();
$("body").append("<br><br>"); //Add some spacing to distinguish between both grids
var grid2 = new grid("b");
grid2.init();
});
</script>