简体   繁体   English

Javascript 用 onClick 更新变量

[英]Javascript update variable with onClick

I've been working on a simple javascript function for hours.我一直在研究一个简单的 javascript function 几个小时。 The intention is that 2 comments are displayed under an article by default, and that 5 are added each time you click on a button.其目的是默认在一篇文章下显示 2 条评论,并且每次单击按钮时添加 5 条评论。

This is my code:这是我的代码:

<div id="reaction1">Comment 1</div>
<div id="reaction2">Comment 2</div>
<div id="reaction3">Comment 3</div>
<div id="reaction4">Comment 4</div>
<p onClick="reactionsfunction()">More reactions</p>

<script>
var reactionsload = 2;
function reactionsfunction(){
    reactionsload = reactionsload + 5;
}
var x = document.querySelectorAll("div[id^='reaction']");
for (var i = 0; i < reactionsload; i++) {
    x[i].style.display = "block";
}
</script>

The for loop works perfectly, but the variable is not updated. for 循环运行良好,但变量未更新。 How do I get the function to update the condition in the for loop by the function?如何让 function 通过 function 更新 for 循环中的条件?

if I understand you correctly, the problem is that your loop run only once when your DOM loaded so all you need is to run this loop each time you fire reactionsfunction like this如果我理解正确,问题是当你的DOM加载时你的循环只运行一次,所以你只需要在每次触发这样的reactionsfunction时运行这个循环

iterate(); // run it once after the page load
var reactionsload = 2;
function reactionsfunction(){
    reactionsload = reactionsload + 5;
    iterate();
}

function iterate(){
  var x = document.querySelectorAll("div[id^='reaction']");
  for (var i = 0; i < reactionsload; i++) {
    x[i].style.display = "block";
 }
}

The problem is not with the variable, it's just that the for loop only runs once, not every single time the p element is clicked.问题不在于变量,而只是 for 循环只运行一次,而不是每次单击 p 元素时。 Instead of what you have, you could put而不是你所拥有的,你可以把

 var reactionsload = 2; function reactionsfunction(){ reactionsload = reactionsload + 5; var x = document.querySelectorAll("div[id^='reaction']"); for (var i = 0; i < reactionsload; i++) { x[i].style.display = "block"; } } var x = document.querySelectorAll("div[id^='reaction']"); for (var i = 0; i < reactionsload; i++) { x[i].style.display = "block"; }
 <div id="reaction1">Comment 1</div> <div id="reaction2">Comment 2</div> <div id="reaction3">Comment 3</div> <div id="reaction4">Comment 4</div> <p onClick="reactionsfunction()">More reactions</p>

I would also like to point out that if you add more to reactionsload, there might not be say 7 elements with div whose ids start with "reaction" so there could be errors.我还想指出,如果您向反应负载添加更多内容,则可能不会有 7 个带有 div 的元素,其 id 以“reaction”开头,因此可能会出现错误。

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

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