Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have number as below

<div class="btn">
    <span class="num-items">1</span>
</div>
<div class="btn">
    <span class="num-items">2</span>
</div>
<div class="btn">
    <span class="num-items">3</span>
</div>
<div class="btn">
    <span class="num-items">4</span>
</div>
<div class="btn">
    <span class="num-items">5</span>
</div>
$('.btn').click(function(){
    var currentEl = [];
    $(this).toggleClass('bg_red');
    currentEl.push($(this));

    if(currentEl.length >=3){
        alert("You can pick only 3 item");
    }
})

I want to add this element to an array every time I clicked on number so that when array length greater or equal to 3, I can alert message.

question from:https://stackoverflow.com/questions/65931017/how-to-add-current-clicked-element-to-an-array-in-jquery

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
114 views
Welcome To Ask or Share your Answers For Others

1 Answer

Adding a log, you will see that currentEl is reset to [] everytime you click, because you redeclare it on every function call

$('.btn').click(function(){
    var currentEl = [];
    $(this).toggleClass('bg_red');
    
    console.log(currentEl)
    
    currentEl.push($(this));

    if(currentEl.length >=3){
        alert("You can pick only 3 item");
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn">
  <span class="num-items">1</span>
</div>
<div class="btn">
  <span class="num-items">2</span>
</div>
<div class="btn">
  <span class="num-items">3</span>
</div>
<div class="btn">
  <span class="num-items">4</span>
</div>
<div class="btn">
  <span class="num-items">5</span>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...