Jquery$(this)是否被jqgrid gridload方法破坏



我希望下面的代码卸载一个javascipt jqgrid,然后加载另一个具有不同选项的网格,包括不同的列

//onload
(function($)
$.fn.myGridFn = function(options){
   $(this).jqGrid('GridUnload');
   $(this).jqGrid(options.gridoptions);

//....
$('#select').change(function(){ 
    switch($(this).val())
    {
      case 'grid1':
            $('#grid').myGridFn({gridoptions:{/*grid1 options*/}});
            break;
      case 'grid2':
            $('#grid').myGridFn({gridoptions:{/*grid2 options*/}});
            break;
    }
   });

})(jQuery);
//...
<table id="grid"></table>

我得到的是网格卸载,然后我必须更改select元素中的选择,然后再次返回以加载新网格。

更新:如果我用实际的元素选择器$("#grid")替换插件中的$(this)-它工作得很好,我不能在我的真实应用程序中这样做,因为该插件被其他几个表元素和网格使用

为未来读者清理:

这里有一种工作小提琴:http://jsfiddle.net/s3MsW/10/

我说"有点"是因为底层代码是可疑的(jqGrid本身)。但我们马上就到。。。第一件事:如果你为插件记录"this",它实际上是jQuery对象,而不是节点。理论上,我们可以用this替换原始代码中的$(this),一切都应该正常。

除非不是。

实际上,您可以使用this来卸载Grid,但该函数会将this保留为一个引用,不指向渲染页面上的表。有一些方法可以显示旧节点仍然存在(http://jsfiddle.net/s3MsW/8是一个测试),但足以说明它不能再用于向页面本身呈现新表。

除了缓存选择器字符串并从头开始重新选择干净的表(即创建一个新的jQuery对象)之外,没有其他真正的选择:

$.fn.myGridFn = function(options){
   var theId = this.selector;
   this.jqGrid('GridUnload'); // reference works for now
   $(theId).jqGrid(options); // reference is broken, so re-select with cached ID
}

如果你认真考虑内存使用,你可能想销毁this(重影节点),但仅仅保留它可能没有真正的危害。

在我看来,您应该将$(this)保存在类似$this的变量中,然后再使用它。问题只是内部

$('#select').change(function(){/*here*/}); // another value of this

所以你应该做

(function($)
$.fn.myGridFn = function(options) {
    var $this = $(this), selector = $this.selector;
    $this.jqGrid('GridUnload');
    $this = $(selector);    // reset $this value
    ...    
    $('#select').change(function() { 
        switch($(this).val()) { // here is $('#select')
          case 'grid1':
                $this.myGridFn({gridoptions:{/*grid1 options*/}});
                ...

此外,一个使用通常启动插件的主体

return this.each( function() { ...

以确保您的插件在类似$(".myGridClass").myGridFn(...)的使用情况下也能工作,在$(".myGridClass")中可以有多个元素。

这个问题很难解决,上面的答案是正确的。

我一直在尝试执行以下操作:

this.jqGrid('GridUnload')
this.('getGridParam'); /* Still returning all the parameters for the grid. */

相反,我做了:

var $t = $(this.selector);
$t.jqGrid('GridUnload');
$t = $(this.selector);
$t.jqGrid('getGridParam'); /* Now empty */

我认为你应该试试

$('#select option:selected).val()// gives the value of the selected option.
$('#select option:selected).text()// gives the text of the selected option.

而不是

$(this).val() 

在开关的括号中

最新更新