简体   繁体   中英

Javascript update variable with onClick

I've been working on a simple javascript function for hours. 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.

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. How do I get the function to update the condition in the for loop by the function?

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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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