javascript - jQuery plug-in to intercept string length, encounters the problem of not being able to correctly obtain the text() in the element
typecho
typecho 2017-06-28 09:28:00
0
2
909

I made a plug-in to intercept the length of a string. When the number of characters exceeds the specified number, the characters are intercepted and the complete content prompt is displayed by following the mouse.
It can be realized when writing the function alone, but after using the following method to make a plug-in, it is found that the content followed by the mouse is the last one, and the content of the last one will be displayed regardless of whether the characters are exceeded, because there are some The content is loaded dynamically, so event delegation is used.

(function($, window, document, undefined) {
    // 创造一个公共变量来构建一个私有方法
    var privateFunction = function() {}
    var methods = {
        // 字符截取,鼠标触发跟随详情提示框
        subString: function (options) {
            return this.each(function(index) {
                var $this = $(this);
                var defaults = {
                    el: '',      // 目标元素
                    charNum: 22,    // 截取字符个数
                    hasDot: true,   // 是否显示省略号
                    // dotColor: '#666'   // 省略号颜色
                    allTextp: '#allText',       // 鼠标跟随完整文本框的p
                    isPrompt: true      // 是否显示提示框
                };
                var settings = $.extend({}, defaults, options),
                    allTextp = settings.allTextp.replace(/[#|.]/g, ''),
                    strText = $(settings.el).eq(index).text(),
                    chineseRegex = /[^\x00-\xff]/g,
                    strLength = strText.replace(chineseRegex, '**').length,
                    newLength = 0,
                    newStr = '',
                    singleChar = '';
                function _subString(str, len, hasDot) {
                    for (var i = 0; i < strLength; i++) {
                        singleChar = str.charAt(i).toString();
                        singleChar.match(chineseRegex) != null ? newLength += 2 : newLength++;
                        if (newLength > len) break;
                        newStr += singleChar;
                    }
                    if (hasDot && strLength > len) newStr += '...';
                    return newStr;
                }
                // 截取字符串
                $this.html(_subString(strText, settings.charNum, settings.hasDot));
                // 鼠标跟随是否显示完整文本框
                if ( (strLength > settings.charNum) && settings.isPrompt ) {
                    $(document).on('mouseover', settings.el, function(event) {
                        if ( settings.allTextp.indexOf('#') != -1 ) $('body').append('<p id="' + allTextp + '" />');
                        if ( settings.allTextp.indexOf('.') != -1 ) $('body').append('<p class="' + allTextp + '" />');
                    });
                    $(document).on('mousemove', settings.el, function(event) {
                        $(settings.allTextp).text(strText).show().css({
                            left: event.pageX + 30,
                            top: event.pageY
                        });
                    });
                    $(document).on('mouseout', settings.el, function(event) {
                        $(settings.allTextp).remove();
                    });
                    // $this.mouseover(function() {
                    //     if ( settings.allTextp.indexOf('#') != -1 ) $('body').append('<p id="' + allTextp + '" />');
                    //     if ( settings.allTextp.indexOf('.') != -1 ) $('body').append('<p class="' + allTextp + '" />');
                    // });
                    // $this.mousemove(function(event) {
                    //     $(settings.allTextp).text(strText).show().css({
                    //         left: event.pageX + 30,
                    //         top: event.pageY
                    //     });
                    // });
                    // $this.mouseout(function() {
                    //     $(settings.allTextp).remove();
                    // });
                }
            });
        }
        };
    $.fn.inCommonUseJsPlugin = function() {
        var method = arguments[0];
        if(methods[method]) {
            method = methods[method];
            arguments = Array.prototype.slice.call(arguments, 1);
        } else/* if( typeof(method) == 'object' || !method ) {
            method = methods.init;
        } else */{
            $.error( 'Method ' +  method + ' does not exist on jQuery.pluginName' );
            return this;
        }
        return method.apply(this, arguments);
    }
})(jQuery, window, document);
typecho
typecho

Following the voice in heart.

reply all(2)
世界只因有你

My brain was confused during work hours. I went home and wrote it again. It was solved. It would be much easier if I changed my thinking!

/**
 * 
 * @authors xxy
 * @date    2017-06-26 19:19:42
 * @url http://www.hifrontend.com
 */

(function($, window, document, undefined) {
    var methods = {
        // 字符截取,鼠标触发跟随详情提示框
        subString: function (options) {
            var $this = $(this);
            var defaults = {
                el: 'li',      // 目标元素
                charNum: 22,    // 截取字符个数
                hasDot: true,   // 是否显示省略号
                // dotColor: '#666'   // 省略号颜色
                allTextp: '#allText',       // 鼠标跟随完整文本框的p
                isPrompt: true      // 是否显示提示框
            };
            var settings = $.extend({}, defaults, options);
            function _subString(str, len, hasDot) {
                var newLength = 0;
                var newStr = "";
                var chineseRegex = /[^\x00-\xff]/g; // 提取中文汉字
                var singleChar = "";
                var strLength = str.replace(chineseRegex, "**").length; // 将中文替换成 ** 并计算长度
                for (var i = 0; i < strLength; i++) {
                    singleChar = str.charAt(i).toString();
                    (singleChar.match(chineseRegex) != null) ? newLength += 2 : newLength++;
                    if (newLength > len) break;
                    newStr += singleChar;
                }
                if (hasDot && strLength > len) newStr += "...";
                return newStr;
            }
            $(settings.el).each(function() {
                var text = $(this).text();
                $(this).attr('data-text', text); 
                $(this).html(_subString(text, settings.charNum, settings.isPrompt));
            });
            // 鼠标跟随是否显示完整文本框
            $(document).on('mouseover', settings.el, function() {
                var allTextLen = $(this).attr('data-text').replace(/[^\x00-\xff]/g, "**").length;
                if ( allTextLen > settings.charNum ) {
                    var allTextp = settings.allTextp.replace(/[#|.]/g, '')
                    if ( settings.allTextp.indexOf('#') != -1 ) $('body').append('<p id="' + allTextp + '" />');
                    if ( settings.allTextp.indexOf('.') != -1 ) $('body').append('<p class="' + allTextp + '" />');
                }
            });
            $(document).on('mousemove', settings.el, function(event) {
                $(settings.allTextp).text( $(this).attr('data-text') ).show().css({
                    left: event.pageX + 30,
                    top: event.pageY
                });
            });
            $(document).on('mouseout', settings.el, function() {
                $(settings.allTextp).remove()
            });
            return this;
        }
    };
    $.fn.inCommonUseJsPlugin = function() {
        var method = arguments[0];
        if(methods[method]) {
            method = methods[method];
            arguments = Array.prototype.slice.call(arguments, 1);
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.pluginName' );
            return this;
        }
        return method.apply(this, arguments);
    }
})(jQuery, window, document);
phpcn_u1582
var settings = $.extend({}, defaults, options),
    allTextp = settings.allTextp.replace(/[#|.]/g, ''),
    strText = $(settings.el).eq(index).text(),
    chineseRegex = /[^\x00-\xff]/g,
    strLength = strText.replace(chineseRegex, '**').length,
    newLength = 0,
    newStr = '',
    singleChar = '';

With this way of writing, allTextp is considered local or global? It is said that some older browsers will consider it global. In this case, it can be explained that the content followed by the mouse is always the last one. From the code point of view, I can't see any other problems that may cause this phenomenon.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template