JQuery插件文件加载但不起作用

时间:2014-08-06 12:59:39

标签: javascript jquery plugins tablesorter

我正在尝试加载tablesorter JQuery插件,我正在使用JQuery版本2.1.1和最新版本的tablesorter。我按以下顺序加载它们:

<script src="javascript/jquery-2.1.1.min.js"></script>
<script src="javascript/jquery.tablesorter.min.js"></script>

我尝试过tablesorter的问题,但没有一个能够正常工作。我通过添加

来测试我有正确的插件文件位置
alert("Plugin File");

位于文件的顶部,这在页面加载时有效。

没有任何插件功能正常工作,我使用此代码对其进行了测试:

$(document).ready(function(e){
  if(jQuery.fn.tablesorter){
    alert("pluginloaded");
   }
     jQuery.tablesorter();
   }
}

警报不起作用,并且firebug报告tablesorter不是函数。

1 个答案:

答案 0 :(得分:0)

我认为这个问题是一系列问题。

  1. 文档就绪函数没有右括号,导致javascript错误导致函数根本无法运行:

    $(document).ready(function(e){
        if (jQuery.fn.tablesorter) {
            alert("pluginloaded");
        }
        jQuery.tablesorter();
    });
    
  2. 第二个问题是没有正确调用tablesorter。第jQuery.tablesorter();行试图调用tablesorter函数,但这只是一个包含所有tablesorter插件函数的对象。

    要实际调用插件,您需要使用jQuery选择器,然后使用tablesorter函数(这就是jQuery.fn.tablesorter工作的原因 - 它是jQuery's alias to the prototype property

    $(function (e) {
        if (jQuery.fn.tablesorter) {
            alert("pluginloaded");
        }
        // jQuery.tablesorter(); // not the way to call the plugin
        $('table').tablesorter();
    });
    
  3. Here is a demo表明它正常运作。