【问题标题】:Converting hard coded JQuery to a plugin - syntax issues将硬编码的 JQuery 转换为插件 - 语法问题
【发布时间】:2012-06-07 15:08:59
【问题描述】:

我有一些 JQuery 可以加载许多元素之一,例如一个 <li> 在许多行列表项中的无序列表中:

  this.randomtip = function(){
        var length = $("#tips li").length;
        var ran = Math.floor(Math.random()*length) + 1;
        $("#tips li:nth-child(" + ran + ")").show();
    };

    $(document).ready(function(){
        randomtip();
    });

但是,我认为将其转换为 JQuery 插件以使其在使用中更具全局性会很好,因此当我需要它用于不同的元素和用例时,我可以简单地调用它。

我意识到我需要取出特定的选择器并将它们转换为$(this),这可能是基于查看其他 JQuery 插件的一些代码。

这是我目前所拥有的,但我遇到了很多语法错误。我在几个小时内尝试了同一件事的许多不同迭代,但没有任何乐趣:

(function ( $ ) {

    $.fn.randomtip = function () {

    var length = $(this).length;
    var ran = Math.floor(Math.random()*length) + 1;
    $(this).find (':nth-child' '+ ran + ')").show();


})(jQuery);

我遇到语法错误的地方是:

$(this).find (':nth-child' '+ ran + ')").show();

【问题讨论】:

    标签: javascript jquery function jquery-plugins syntax


    【解决方案1】:

    $(this).find() 行有一些拼写错误。以下是正确的版本:

    (function ( $ ) {
        $.fn.randomtip = function () {
        var length = $(this).length;
        var ran = Math.floor(Math.random() * length) + 1;
        $(this).find (':nth-child('+ ran + ')').show();
    })(jQuery);
    

    【讨论】:

    • 谢谢,太好了,不过我需要在最后再添加一个右括号。
    【解决方案2】:

    有语法问题

    $(this).find (':nth-child' '+ ran + ')").show();
    

    也许你想要这个?

    $(this).find (':nth-child(' + ran + ')').show();
    

    【讨论】:

      猜你喜欢
      • 2015-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 2013-06-23
      相关资源
      最近更新 更多