从一些jQuery插件外部调用插件函数

时间:2017-12-03 12:14:11

标签: jquery html

我正在使用一个表情符号jQuery插件来评价一些文章。 在表情符号评级插件文件中有一个功能用于显示基于点击表情符号的计数。我需要从外部调用插件的特定功能。 这里的想法是根据给定的数量填充表情符号,以便不用悬停。 以下是插件文件:

/**
 *********************************
 * Emotions Rating - Yanci Nerio *
 *********************************
 * Emotions Rating
 * Version: 1.0.0
 * URL: https://github.com/YanNerio/emotion-ratings
 * Description: This plugin allows you to create ratings using emojis
 * Requires: >= 1.9
 * Author: Yanci Nerio (www.yancinerio.com)
 * License: MIT
 */

;(function($, document, window, undefined) {

    "use strict";

    var pluginName = 'emotionsRating';
    var $element;
    // Default options for the plugin
    var defaults = {
        bgEmotion: "happy",
        emotionsCollection: ['angry','disappointed','meh', 'happy', 'inLove'],
        count: 5,
        color: "red",
        emotionSize: 30,
        inputName: "rating",
        emotionOnUpdate: null
    };
    //the collection of emotions to show on the ratings
    var emotionsArray = {
          angry: "😠",
          disappointed: "😞",
          meh: "😐", 
          happy: "😊",
          smile: "😃",
          wink: "😉",
          laughing: "😆",
          inLove: "😍",
          heart: "❤",
          crying: "😢",
          star: "⭐",
        };
    //the collection of emotions to show on the ratings
    var colorsArray = {
            gold: "#d0a658;",
            red: "#cb2a2a;",
            blue: "#337ab7;", 
            green: "#26bf78;",
            black: "#00000;",
            brown: "#916a3a;",
            pink: "#f21f6d;",
            purple: "#ba27bd",
            orange: "#f89e5e;"
    };
    var clicked = false;

    // Plugin constructor
    function Plugin(element, options) {
        this.element = $("#element");//element;
        // Merge the options given by the user with the defaults
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }
    
    //Avoiding conflicts with prototype
    $.extend(Plugin.prototype = {
        // Public functions accessible to users
        // Prototype methods are shared across all elements
        // You have access to this.settings and this.element
        init: function() {
            $element = $(this.element);
            this.count = 0;
            this.emotionStyle();
            this.renderEmotion();            
            this.manageHover();
            this.manageClick();
        },
        emotionStyle: function() {
            var styles = ".emotion-style{margin-right:3px;border-radius: 50%;cursor:pointer;opacity:0.3;display: inline-block;font-size:"
                 + this.settings.emotionSize +"px; text-decoration:none;line-height:0.9;text-align: center;color:"+colorsArray[this.settings.color]+"}";
            $element.append("<style>" + styles + "</style>");
        },
        renderEmotion: function () {
            var count = this.settings.count;
            var bgEmotion = emotionsArray[this.settings.bgEmotion];
            var container = "<div class='emotion-container'>";
            var emotionDiv;

            for (var i = 0; i < count; i++) {
                emotionDiv = "<div class='emotion-style' data-index='" + i + "'>"+bgEmotion+"</div>";
                container += emotionDiv;
            }
            container += "</div>";

            $element.append(container);
        },
        clearEmotion: function(content) {
            $element.find(".emotion-style").each( function() {
                $(this).css("opacity", 0.3);
                var bgEmotion = emotionsArray[content];
                $(this).html(bgEmotion);
            });
        },
        showEmotion: function(count) {
            this.clearEmotion(this.settings.bgEmotion);
            var emotion = getEmotion(this.settings.emotions,count);
            for (var i = 0; i < count; i++) {                
                $element.find(".emotion-style").eq(i).css("opacity", 1);
                $element.find(".emotion-style").eq(i).html(emotion);
            }
        },
        manageHover: function() {
            var self = this;

            $element.on({
                mouseenter: function() {
                    var count = parseInt($(this).data("index"), 10) + 1;

                    if (clicked) {
                       // return;
                    }
                    self.showEmotion(count);
                },
                mouseleave: function() {
                    if (!clicked) {
                        self.clearEmotion();
                    }
                }
            }, ".emotion-style" );
        },
        manageClick: function() {
            var self = this;
            $element.on("click", ".emotion-style", function() {
            var index = $(this).data("index"),
                count = parseInt(index, 10) + 1;

                self.showEmotion(count);
                self.count = count;

                if (!clicked) {
                    self.appendInput(count);
                    clicked = true;
                } else {
                    self.updateInput(count);
                }
                if ($.isFunction(self.settings.onUpdate)) {
                    self.settings.onUpdate.call(self, count);
                }
            });
        },        
        appendInput: function(count) {
            var _input = "<input type='hidden' class='emoji-rating'" + 
                    " name='" + this.settings.inputName + 
                    "' value='" + count + "' />";
			alert(count);
            $element.append(_input);
        },
        updateInput: function(count) {
            var _input = $element.find("input.emoji-rating");

            _input.val(count);
			alert(count);
        }
    });

    $.fn[pluginName] = function(options) {
        return this.each(function() {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
            }
        });
    };

    var getEmotion = function(_emotions,count) {
        var emotion;
        emotion = emotionsArray[_emotions[count-1]];
        return emotion;
    }

})(jQuery, document, window);

然后在我的html页面中,我试图访问manageclick函数,如下所示:

<div class="container">
    <h1>jQuery Emotion Ratings Plugin Demo</h1>
    
    <div id="element1"></div>
</div>
<script src="@Url.Content("~/Content/Ratings/emotion-ratings.js")"></script>
<script src="@Url.Content("~/Content/Ratings/emoji_ga.js")"></script>
<script>

 
  var test = $("#element1").emotionsRating({});
  $.test.manageClick();
  
</script>

以上emotion-rating.js文件中使用了插件代码。

但是得到错误管理未定义的点击。 我怎么能在外部访问这个功能?

1 个答案:

答案 0 :(得分:1)

我阅读了这个插件的源代码,注意到它没有选项或公共方法来根据给定的数量来填充表情符号,但仍然有一个替代方案可以满足您的要求(请注意上面使用的源代码)已经从original code

进行了修改
  1. 简单但推荐一个。您可以通过执行此操作手动触发点击事件
  2. $('#element .emotion-style:eq('+count+')').click()

    'element'是dom容器的id attr,用于初始化插件

    1. 或者您可以修改源代码以提供打开选项。当设置该选项时,触发init方法中的click事件