Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将硬编码JQuery转换为插件-语法问题_Javascript_Jquery_Function_Jquery Plugins_Syntax - Fatal编程技术网

Javascript 将硬编码JQuery转换为插件-语法问题

Javascript 将硬编码JQuery转换为插件-语法问题,javascript,jquery,function,jquery-plugins,syntax,Javascript,Jquery,Function,Jquery Plugins,Syntax,我有一些JQuery,它加载了许多元素中的一个,例如,一个在一个无序列表中,从许多行列表项中取出,如下所示: this.randomtip = function(){ var length = $("#tips li").length; var ran = Math.floor(Math.random()*length) + 1; $("#tips li:nth-child(" + ran + ")").show(); };

我有一些JQuery,它加载了许多元素中的一个,例如,一个
  • 在一个无序列表中,从许多行列表项中取出,如下所示:

      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插件,使其在使用中更具全局性,这样当我需要它用于不同的元素和用例时,我就可以简单地调用它

    我意识到我需要取出特定的选择器并将它们转换为
    $(这)
    ,这可能是基于查看其他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();
    

    中存在语法问题

    $(this).find (':nth-child' '+ ran + ')").show();
    
    也许你想要这个

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

    您在
    $(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);
    

    谢谢,这是伟大的,我需要添加一个更多的结束括号虽然。