【问题标题】:Javascript - For Loop for maxLength on P TagJavascript - 用于 P 标签上的 maxLength 的 For 循环
【发布时间】:2018-09-20 01:46:09
【问题描述】:

我在这里有这个解决方案,将所选 P 标记的字符限制为 125 个字符,但是它仅适用于循环中的第一个子项,如何编辑以下代码以在 For 循环中工作?我用一些 jQuery 尝试了一些解决方案,但没有找到任何可行的方法。

感谢您的帮助!

function truncateText(selector, maxLength) {

    var element = document.querySelector(".hp-um-description")
     for (element = element) {
        var truncated = element.innerText;

        if (truncated.length > maxLength) {
            truncated = truncated.substr(0,maxLength) + '...';
        }
        return truncated;  
     }
    }

    $(".hp-um-description").each(function(){
      document.querySelector('.hp-um-description').innerText = truncateText('.hp-um-description', 125);
    });

【问题讨论】:

    标签: javascript jquery loops for-loop maxlength


    【解决方案1】:

    您可以使用 jQuery .text() 来避免循环并非常干净地实现这一点。

    function truncateText(selector, maxLength) {
      $(selector).text((i, txt) => txt.length > maxLength ? txt.substr(0,maxLength) + "..." : txt);
    };
    
    truncateText(".hp-um-description", 100);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p class="hp-um-description">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris feugiat ipsum massa, et sagittis enim tempus id. Mauris nisl turpis, pellentesque scelerisque congue nec, faucibus vel arcu.</p>
    
    <p class="hp-um-description"> Fusce id ultrices nibh. Suspendisse sit amet felis lobortis, rhoncus ex eu, fringilla lacus.</p>
    
    <p class="hp-um-description">Suspendisse sit amet felis lobortis, rhoncus ex eu, fringilla lacus. Duis vehicula placerat sapien, ac consectetur dolor egestas eget.</p>

    上面的代码将遍历选择器满足的所有元素并应用一个函数。这一行决定了它是否应该被截断:

         txt.length > maxLength ?    txt.substr(0,maxLength) + "..."     :         txt
    //(If length exceeds maxlength)     (truncate and add ...)         (else)    (leave the text as-is)
    

    如果您也希望能够截断 string,您可以改用以下代码:

    String.prototype.truncate = function(maxLength) {
      var t = this.toString();
      return t.length > maxLength ? t.substr(0, maxLength) + "..." : t;
    };
    
    function truncateText(selector, maxLength) {
      $(selector).text((i, txt) => txt.truncate(maxLength));
    };
    
    //Truncate an existing element's text
    truncateText(".hp-um-description", 100);
    
    //Truncate a string
    console.log("This is a long string that exceeds 30 characters.".truncate(30));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p class="hp-um-description">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris feugiat ipsum massa, et sagittis enim tempus id. Mauris nisl turpis, pellentesque scelerisque congue nec, faucibus vel arcu.</p>
    
    <p class="hp-um-description"> Fusce id ultrices nibh. Suspendisse sit amet felis lobortis, rhoncus ex eu, fringilla lacus.</p>
    
    <p class="hp-um-description">Suspendisse sit amet felis lobortis, rhoncus ex eu, fringilla lacus. Duis vehicula placerat sapien, ac consectetur dolor egestas eget.</p>

    【讨论】:

    • 谢谢你!工作就像一个魅力,我认为 jQuery 将是避免复杂化的好方法。干杯:)
    • 如何将其合并到 .text() 字段中?例如:

      ' + $(this).find("attribute[id='19']").text() + '

    • @JLawless 我上面写的函数只适用于页面上已经存在的元素。如果您要截断字符串,我可以编辑我的问题以提供其他方法。
    • @JLawless 如果您查看我的更新,第二个示例添加了一个 String.truncate 函数,您可以在任何字符串上使用该函数。将函数应用于您的评论将如下所示:$(this).find("attribute[id=19"]).text().truncate(100)。也就是说,不确定attribute[id=19] 到底应该做什么。如果您通过 ID 查找元素,则不需要使用 .find 或属性 - 只需 $("#19").text() 即可。
    • 该属性以 XML 元素的 ID 为目标,因为我正在使用 jQuery 将 XML 中的信息解析为可显示的格式。你的更新就像一种享受,谢谢!
    【解决方案2】:

    试试这个代码:

    function truncateText(element, maxLength) {
        var truncated = element.innerText;
        if (truncated.length > maxLength)
            truncated = truncated.substr(0,maxLength) + '...';
        return truncated;
    }
    $(function() {
        $(".hp-um-description").each(function(i,obj) {
            obj.innerText = truncateText(obj, 125);
        });
    });
    

    【讨论】:

    • 谢谢你,这也做得很好!
    【解决方案3】:

    在 vanilla JavaScript 中,您可以通过以下方式处理此问题...

    var maxLength = 125;
    
    /* select elements as an Array 
       and iterate with Array.forEach() */
    
    [].slice.call(document.querySelectorAll(".hp-um-description")).forEach(function(el) {
        /* 'el' => each ".hp-um-description" element */
    
        /* attempt truncation */
        el.innerText = el.innerText.slice(0, maxLength);
        /* if el.innerText.length is shorter than
           'maxLength' the whole String will be returned (unchanged),
           otherwise the String will be truncated (modified) */
    });
    

    JQuery .each() 函数中的el 变量的等价物绑定到回调的this 属性,像这样...

    $(".hp-um-description").each(function() {
        /* $(this) => each ".hp-um-description" element */
    
        var el = $(this);
    
        /* apply the same conditions as above */
        el.text( el.text().slice(0, maxLength) ); 
    });
    

    希望有所帮助:D

    见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 2020-10-24
      • 2021-09-04
      • 2019-06-05
      • 2021-01-08
      • 2015-12-31
      • 2020-11-29
      相关资源
      最近更新 更多