【问题标题】:Jquery plugin $.fn.myplugin not workingJquery 插件 $.fn.myplugin 不工作
【发布时间】:2012-08-24 10:01:06
【问题描述】:

我可能犯了一个非常简单的错误,但我很难弄清楚为什么它不起作用。

这是代码:http://jsfiddle.net/HthCa/

更新:这是我的实际代码..

<script type="text/javascript" src="scripts.js"></script>
<script type="text/javascript">
    $(function() {
        $('#test').customTabs();
    })
</script>

scripts.js

$.fn.customTabs = function() {
    alert($(this).html());
}

【问题讨论】:

标签: jquery plugins


【解决方案1】:

你确定你像这样从 jquery 选择器对象访问它吗

$("some selectors").myPlugin()

如果你尝试过这个

$.myPlugin() // it won't work

没用

【讨论】:

    【解决方案2】:

    在您的代码中:

    $('#test').customTabs();
    
    $.fn.customTabs = function() {
        alert($(this).html());
    };
    

    您在定义它之前调用了$.fn.customTabs()。试试吧:

    $.fn.customTabs = function() {
        alert(this.html());
    };
    
    $('#test').customTabs();
    

    请注意,您不需要在插件方法中将$ 应用于this,因为this 已经是一个jQuery 对象(调用该方法的对象)。

    【讨论】:

    • 谢谢!在我的网站上查看我对实际代码的更新。它们的顺序正确..
    • @Noah,我想你在scripts.js 之前包含了jQuery?您能发布您收到的确切错误消息吗?
    • 是的,在我调用 scrips.js 之前调用了 jquery。我在我的 iPad 上使用 Koder 应用程序执行此操作,我没有收到任何错误。我在之前和之后设置了警报,以检查错误发生的位置以及在调用插件时发生的错误。
    • @Noah,对不起,我很困惑:你是not getting any errors 还是at the call to the plugin
    • 而这些都在HTML页面的头部
    【解决方案3】:

    把你的代码写成这样

    $.fn.customTabs = function() {
        alert($(this).html());
    };
    $('#test').customTabs();
    

    $.fn.customTabs = function() {
        alert($(this).html());
    };
    $(function() { // <-- inside a dom ready
        $('#test').customTabs();
    });​
    

    原因是您尝试使用尚未定义的函数,如控制台中所述 Uncaught TypeError: Object [object Object] has no method 'customTabs'

    【讨论】:

      【解决方案4】:

      把新的函数定义放在你调用它的地方。

      $.fn.customTabs = function() {
          alert($(this).html());
      };
      $('#test').customTabs();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-03
        • 1970-01-01
        • 2017-01-13
        相关资源
        最近更新 更多