Search code examples
javascriptjshint

Functions declared within loops referencing an outer scoped variable may lead to confusing


This is a jshint warning question.How can I solve this problem?

var comment_btn=document.querySelector('.comment_button');
var comment_ul=document.querySelector('.comment_ul');
var comment_text=document.querySelector('#comment');

comment_btn.onclick = function(){
    var comment_li = document.createElement('li');
    comment_li.className = 'comment_li';
    if(comment_text.value != '') {
        comment_li.innerHTML = comment_text.value + "<a class='comment_a' href='javascript:;'>Delete</a>";
        comment_ul.insertBefore(comment_li,comment_ul.children[0]);
        var del = document.querySelectorAll('.comment_a');
        for (var i = 0; i < del.length; i++) {
            del[i].onclick = function() {
                comment_ul.removeChild(this.parentNode);
            };
        }
    }
    else {
        alert('Please input!');
    }
};

Warning:
Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (comment_ul) (W083)jshint(W083)

I really can't think of a solution,please help me.


Solution

  • Every time you add a new li, you are selecting EVERY delete anchor and adding another click event to it.

    You should not be looping at all. You should just be selecting the anchor in the li you create and attach the event to that.

    const comment_ul = document.querySelector("ul");
    const comment_text = document.querySelector("#comment_text");
    
    
    comment_btn.addEventListener('click', function() {
      if (!comment_text.value.length) {
        alert('Please input!');
        return;
      }
    
      var comment_li = document.createElement('li');
    
      comment_li.className = 'comment_li';
    
      comment_li.innerHTML = comment_text.value + "<a class='comment_a' href='javascript:;'>Delete</a>";
    
      comment_ul.insertBefore(comment_li, comment_ul.children[0]);
    
      var del = comment_li.querySelector('.comment_a');
      del.addEventListener('click', function(evt) {
        evt.preventDefault();
        comment_ul.removeChild(this.parentNode);
      });
    
    });
    <ul></ul>
    
    <input type="text" id="comment_text" />
    <button id="comment_btn">Add</button>