如果textlength>更改innerHTML值的Javascript代码250

时间:2015-10-23 14:41:47

标签: javascript

for(y=0;y<3;y++)
{
var Text = 0;
var TextLength = 0;
var Text = document.getElementsByClassName("Introduction")[y].innerHTML;
var TextLength = Text.length;

    if(TextLength > 250){
        document.getElementsByClassName("Read_More")[y].innerHTML = "Read More";
    }
    else{
        document.getElementsByClassName("Read_More")[y].innerHTML = "";
    }
}

此代码用于运行两次,每次计算字符的长度/数量,在“&#39; p&#39;他的班级是&#34;简介。&#34;

其中有三个,但由于编号从0开始,而不是1,因此代码表示&#34; y&lt; 3。&#34;如果TextLength的值(即&#39; p class =&#34;简介&#34;&#39;中的字符数)大于250,则&#39; p class =&#中的文字34; READ_MORE&#34;&#39;应该是&#34;阅读更多。&#34;

如果不是,它将保持为空。 &#39; p = =#34;简介&#34;&#39;和&#39; p class =&#34; Read_More&#34;&#39;是相同的,如果前者需要满足条件,代码将在相应的后一个元素中执行。

虽然我已经在在线调试器上尝试了这个代码,但没有检测到任何错误,并且在线网页设计工具上,它按照预期的方式工作,一旦我在浏览器上尝试它,它就不起作用了。如果有人能帮助我,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

我希望你的意思是:

window.onload = function() {
  var intros= document.getElementsByClassName("Introduction"),
      mores= document.getElementsByClassName("Read_More");
  for (var i = 0; i < intros.length; i++) {
    var text = intros[i].innerHTML;
    var textLength = text.length;
     mores[i].innerHTML=textLength>250?"Read More":"";
  }
}
<p class="Introduction">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris magna ligula, sagittis at velit quis, laoreet rhoncus metus. Praesent ac aliquam enim, quis fringilla nunc. Proin eget viverra ligula, a blandit neque. Quisque finibus luctus elementum.</p><p class="Read_More"></p>
<hr />
<p class="Introduction">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris magna ligula, sagittis at velit quis, laoreet rhoncus metus. Praesent ac aliquam enim, quis fringilla nunc. Proin eget viverra ligula, a blandit neque. Quisque finibus luctus elementum. Donec sed.</p><p class="Read_More"></p>
<hr />
<p class="Introduction">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris magna ligula, sagittis at velit quis, laoreet rhoncus metus. Praesent ac aliquam enim, quis fringilla nunc. Proin eget viverra ligula, a blandit neque.</p><p class="Read_More"></p>