使用javascript子字符串更改innerHTML

我正在尝试使用 javascript 子字符串读取更多按钮,但我的代码不起作用,我可以隐藏文本,但无法在单击时显示更多内容


<p class="pr">More than 200</p>

<button class="btn">Read more</button>

<script>

  var pr = document.querySelectorAll('.pr');

  var btn = document.querySelectorAll('.btn');


  for (var i = 0; i < pr.length; i++) {

    if(pr[i].innerHTML.length >= 200){

      var showLess = pr[i].innerHTML.substring(0, 200);

      pr[i].innerHTML = showLess;

    }

    btn.addEventListener('click', showMore);


    function showMore(){

      var showMore = pr[i].innerHTML.substring(0, );

      pr[i].innerHTML = showMore;

    }

  }

</script>


慕森王
浏览 232回答 3
3回答

智慧大石

首先,你应该将文本存储在一个变量中,因为如果你缩短它,javascript 不会记住第一个文本:var&nbsp;text&nbsp;=&nbsp;pr[i].textContent;&nbsp;//&nbsp;make&nbsp;this&nbsp;the&nbsp;first&nbsp;thing&nbsp;in&nbsp;the&nbsp;for&nbsp;loop然后,而不是指pr[i].innerHTML.substring&nbsp;使用text.substring(仅在获取值时,而不是在设置时)。我希望这会奏效,还没有测试过(在我的手机上写)。

森栏

使用Id代替类的更简单的版本。let pr = document.getElementById('pr');let btn = document.getElementById('btn');let actualText = pr.innerHTML;&nbsp;if(pr.innerHTML.length >= 200){&nbsp; pr.innerHTML =&nbsp; pr.innerHTML.substring(0, 200);&nbsp; btn.addEventListener('click', () => { pr.innerHTML = actualText;});}<p id="pr">This is basic test content which length is More than 200, This is basic test content which length is More than 200, This is basic test content which length is More than 200, This is basic test content which length is More than 200, This is basic test content which length is More than 200, This is basic test content which length is More than 200, This is basic test content which length is More than 200</p><button id="btn">Read more</button>是的,您需要在更新innerHTML元素之前存储原始文本内容。

函数式编程

您正在innerHTML使用短字符串覆盖 ,因此您需要将原始值保存在变量中。在我的代码片段中,我将原始字符串保存在more变量中。此外,document.querySelectorAll('.btn');返回一个NodeList不能直接附加事件侦听器的对象,您需要遍历每个节点并将其添加到这些节点中。在你的代码中得到一个TypeError在addEventListener这样的回调并没有连接到呼叫click事件。最后,不要使用innerHTML用途,textContent因为这innerHTML是一项昂贵的操作。在这里阅读更多。Element.innerHTML 返回 HTML,正如其名称所示。有时人们使用 innerHTML 在元素内检索或写入文本,但 textContent 具有更好的性能,因为它的值不会被解析为 HTML。此外,使用 textContent 可以防止 XSS 攻击。var pr = document.querySelectorAll('.pr');var btn = document.querySelectorAll('.btn');for(let i =0; i<pr.length; i++){&nbsp; let more = pr[i].textContent;&nbsp; if(more.length >= 5){&nbsp; &nbsp; let showLess = more.substring(0, 5);&nbsp; &nbsp; pr[i].textContent = showLess;&nbsp; }&nbsp; btn.forEach(b => b.addEventListener('click', () => {&nbsp; &nbsp; &nbsp;console.log(more);&nbsp; &nbsp; &nbsp;pr[i].textContent = more;&nbsp; }));&nbsp;&nbsp;}&nbsp;&nbsp;<p class="pr">More than 200</p><button class="btn">Read more</button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript