Javascript - 用于 P 标签上 maxLength 的循环

Javascript - For Loop for maxLength on P Tag

我这里有这个解决方案,将所选 P 标签的字符限制为 125 个字符,但它只适用于循环中的第一个 child,我如何编辑以下代码以在对于循环?我尝试了一些 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);
    });

您可以使用 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>

试试这个代码:

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);
    });
});

在原版 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

参见: