我创建了一个 jqGrid,其中包含一些字段,例如:
job_id、姓名等
我想做的是,当单击 job_id 列中的值时,它将重定向到:
job.php?job_id=(他们点击的值)
我首先尝试使用以下内容作为我的 colModel:
{ name:'job_id', index:'job_id', edittype:'select', formatter:'showlink',
formatoptions:{baseLinkUrl:'job.php'}, width:50, align:'center' }
但是这会导致重定向到:
job.php?job_id=(row_id)
我做了一些搜索,发现了该软件开源版本的开发人员的帖子,他建议使用以下 colModel 和附加 JS:
{ name:'job_id', index:'job_id', edittype:'select', formatter:'showlink',
formatoptions:{baseLinkUrl:'#'}, width:50, align:'center' }
loadComplete: function() {
var myGrid = $("#home_list");
var ids = myGrid.getDataIDs();
for (var i = 0, idCount = ids.length; i < idCount; i++) {
$("#"+ids[i]+" a",myGrid[0]).click(function(e) {
var hash=e.currentTarget.hash;// string like "#?id=0"
if (hash.substring(0,5) === '#?id=') {
var id = hash.substring(5,hash.length);
var text = this.textContent;
location.href="job.php?id="+text;
}
e.preventDefault();
});
}
}
但这与 IE 不兼容。除此之外,当在 jqGrid 中显示大量行时,加载时间非常长,例如 500 行需要 5 秒以上。
我将继续努力,但这是否是其他人已经做过的事情?
最佳答案
您使用了 my old answer 中的代码示例所以我决定我应该回答你的问题。
我同意对 loadComplete
代码性能的批评。所以我对你的问题+1。长循环内部的构造 $("#"+ids[i]+"a", myGrid[0])
运行速度可能非常慢。如果使用以下内容,就可以轻松解决问题
var getColumnIndexByName = function (columnName) {
var cm = $(this).jqGrid("getGridParam", "colModel"), l = cm.length, i;
for (i = 0; i < l; i++) {
if (cm[i].name === columnName) {
return i; // return the index
}
}
return -1;
};
var myGrid = $("#list");
myGrid.jqGrid({
...
loadComplete: function () {
var i = getColumnIndexByName.call(this, 'Subcategory');
// nth-child need 1-based index so we use (i+1) below
$("tbody>tr.jqgrow>td:nth-child(" + (i+1) + ")>a", this).click(function (e) {
var hash=e.currentTarget.hash;// string like "#?id=0"
if (hash.substring(0,5) === '#?id=') {
var id = hash.substring(5, hash.length);
var text = this.textContent || this.innerText;
alert("clicked the row with id='"+id+"'. Link contain '"+text+"'");
location.href = "http://en.wikipedia.org/wiki/" + text;
}
e.preventDefault();
});
}
});
可以看到the demo的改进版本与 the original demo 完全相同。为了显示该方法在 1000 行上的性能,我创建了 one more demo 。可以看到,新方法见效很快。
现在回到你的主要问题。如果您写下custom formatter,我们将获得最佳性能和 unformatter而不是使用预定义的格式化程序 showlink 。代码大概如下:
formatter: function (cellvalue, options, rowObject) {
return "<a href=\"job.php?job_id=" + rowObject.job_id + "\">" + cellvalue + "</a>";
},
unformat: function (cellvalue, options, cellobject) {
return cellobject.job_id;
}
确切的代码取决于您使用的datatype
、是否使用loadonce:true
以及您使用的jsonReader
。例如,在您的情况下, rowObject
是数组,您必须使用
相应数据字段的数组索引(如 rowObject[4]
),而不是 rowObject.job_id
。
更新:我认为最好的实现方式是使用 onCellSelect 或 beforeSelectRow,而不是将单击事件绑定(bind)到列中的每个元素。我建议阅读以下答案以了解详细信息:this one , another one和 one more old answer .
关于jquery - 使用 GET 从 jqGrid 中的列值链接到新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5010761/