【问题标题】:Trying to truncate a string and replace with ... in JQuery试图在 JQuery 中截断字符串并用 ... 替换
【发布时间】:2012-06-15 12:59:31
【问题描述】:

编辑 2:

我刚刚意识到我的 HTML 只显示艺术家和歌曲,而不是专辑,这就是为什么当我有

alert(album);

在那里我得到了意想不到的结果。 jQuery 修剪现在按预期工作。 脸红 感谢您的回答,我将为其他脚本保留。

我正在使用 JQuery 来获取 lastfm 用户播放的最后 10 首歌曲并显示它们。

我想将专辑名称截断为 x 个字符并替换为 ...

字符串是:

album = item.album['#text'];

并显示在这里:

$current.find('[class=lfm_album]').append(album);

我尝试过使用:

var shortText = jQuery.trim(album).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";

但它只显示完整的专辑字符串,似乎没有多少摆弄或 javascript 起作用。

编辑:

我刚试过

album = item.album['#text'];
alert(album);

查看它的想法,我得到了一些与脚本生成的任何其他字符串都不匹配的结果,所以现在真的卡住了!

完整脚本如下:

/*---------------
 * jQuery Last.Fm Plugin by Engage Interactive
 * Examples and documentation at: http://labs.engageinteractive.co.uk/lastfm/
 * Copyright (c) 2009 Engage Interactive
 * Version: 1.0 (10-JUN-2009)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.3 or later
---------------*/

(function($){
    $.fn.lastFM = function(options) {

        var defaults = {
            number: 5,
            username: 'xxxxxxx',
            apikey: 'xxxxxxxx',
            artSize: 'medium',
            noart: 'images/noartwork.gif',
            onComplete: function(){}
        },
        settings = $.extend({}, defaults, options);

        var lastUrl = 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user='+settings.username+'&api_key='+settings.apikey+'&limit='+settings.number+'&format=json&callback=?';
        var $this = $(this);

        var container = $this.html();

        $this.children(':first').remove();

        if(settings.artSize == 'small'){imgSize = 0}
        if(settings.artSize == 'medium'){imgSize = 1}
        if(settings.artSize == 'large'){imgSize = 2}

        this.each(function() {

            $.getJSON(lastUrl, function(data){ 
                $.each(data.recenttracks.track, function(i, item){

                    if(item.image[1]['#text'] == ''){
                        art = settings.noart;
                    }else{
                        art = stripslashes(item.image[imgSize]['#text']);
                    }

                    url = stripslashes(item.url);
                    song = item.name;
                    artist = item.artist['#text'];
                    album = item.album['#text'];
// this is the part where I try to truncate "album"
var shortText = $.trim(album).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";




                    $this.append(container);

                    var $current = $this.children(':eq('+i+')');

                    $current.find('[class=lfm_song]').append(song);
                    $current.find('[class=lfm_artist]').append(artist);
                    //$current.find('[class=lfm_album]').append(album);
                    $current.find('[class=lfm_album]').append(shortText);
                    $current.find('[class=lfm_art]').append("<img src='"+art+"' alt='Artwork for "+album+"'/>");
                    $current.find('a').attr('href', url).attr('title', 'Listen to '+song+' on Last.FM').attr('target', '_blank');

                    //callback
                    if(i==(settings.number-1)){
                        settings.onComplete.call(this);
                    }

                });
            });
        });
    };

    //Clean up the URL's
    function stripslashes( str ) {   
        return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
    }
})(jQuery);

感谢您的帮助。

【问题讨论】:

  • 您的修剪功能正常工作:查看此示例jsfiddle.net/b7yyC/2
  • blush.. 我刚刚意识到我的 html 输出的是艺术家和歌曲而不是专辑

标签: jquery truncate


【解决方案1】:
if (album.length > 10) {
        album = album.substring(0, 10) + "...";
    }

【讨论】:

    【解决方案2】:

    如果您想在第 10 个字符后用空格截断专辑/标题,您可以使用 indexOf 方法

    var album = "   This is the're long title of the album    ";
    
    album = $.trim(album); //make sure to trim the album first
    if (album.length > 10) {
      //the indexOf will return the position of the first space starting from the 10th
       alert(album.substring(0, album.indexOf(' ',10)) + "...");
    }
    

    来源MDN

    【讨论】:

      【解决方案3】:
      album = item.album['#text'];
      var x = 10;
      
      if(str.length > x) {
          album = str.substr(0,x) + "...";    
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多