简体   繁体   English

Javascript-仅在第一段中限制字符

[英]Javascript - limit characters only on first paragraph

I have aa div with multiple p elements within it. 我有一个div里面有多个p元素。 I wanted to know how I can limit the character length of the first p element within each div of the same class. 我想知道如何限制同一类的每个div中第一个p元素的字符长度。

HTML 的HTML

<div class="el">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates natus dignissimos architecto deserunt totam ullam, nulla ipsum cumque alias possimus dicta officiis provident mollitia modi tempore officia porro tenetur dolor.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias quidem, ad doloribus reiciendis debitis sit suscipit est cumque voluptates corporis adipisci consectetur, perspiciatis quo pariatur minima inventore omnis deleniti assumenda!</p>
</div>

Javascript (so far) Javascript(到目前为止)

var quote = document.querySelectorAll('.el');

for (var i=0, len=quote.length; i < len; i++) {

  var text = quote[i].firstElementChild.innerHTML;
  console.log(text);

  if(text.length > 150) {
    console.log("condition met");
    text = text.substring(0,150) + '<a href="#">Read more</a>';
  }
}

I think I'm right up until I try to edit the length of text itself. 我想我是对的,直到我尝试编辑文本本身的长度。 But help would be appreciated along with explanation of what I'm doing wrong. 但是,在解释我做错事情时,我们将不胜感激。 I've set up a fiddle for your convenience . 为了您的方便我开了一个小提琴。

Check this i have checked all p element length 检查我已经检查了所有p元素的长度

  var quote = document.querySelectorAll('.el p');

for (var i=0, len=quote.length; i < len; i++) {

  var text = quote[i].innerHTML;
  console.log(text);

  if(text.length > 150) {
    console.log("condition met");
    text = text.substring(0,150) + ' <a href="#">Read more</a>';
    quote[i].innerHTML = text;
  }
}

just edit your script as follow: 只需按照以下步骤编辑脚本:

 if(text.length > 150) { console.log("condition met"); text = text.substring(0,150) + '<a href="#">Read more</a>'; quote[i].firstElementChild.innerHTML= text; // update your element } 

I couldn't get the suggestions working as I wanted although the they did lead me to this jsFiddle . 尽管我的建议确实将我引向了jsFiddle,但我却无法按照我的意愿进行操作

Js: Js:

var quote = document.querySelectorAll('.el');

for (var i=0, len=quote.length; i < len; i++) {

  var text = quote[i].firstElementChild;

  if(text.innerHTML.length > 200) {
    text.innerHTML = text.innerHTML.substring(0,200) +  '... <a href="/page-name/">Read more</a>';
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM