0

I define a 'rtextDiv' as a global variable for the two eventListener function after it,but firefox debugger says me that the rtextDiv is undefined at the second eventListener function. Am I wrong somewhere?

  • Error occurs on the line that I marked with **

Here is the code:

var rtextDiv;
// setup filter change event for the last added expression results
for (var i = 0; i < dmsg.getElementsByClassName('refilter').length; i++) {
    var refilterInput = dmsg.getElementsByClassName('refilter')[i];
    refilterInput.addEventListener('keyup', function () {
        rtextDiv = refilterInput.parentNode.parentNode.getElementsByClassName('rtext')[0];
        while (rtextDiv.firstChild) {
            rtextDiv.removeChild(rtextDiv.firstChild);
        }
        fil1 = filteredPropertiesTable(res, refilterInput.value);
        rtextDiv.appendChild(fil1);
    });
}

for (var i = 0; i < dmsg.getElementsByClassName('propfilter').length; i++) {
    var refilterInput2 = dmsg.getElementsByClassName('propfilter')[i];
    refilterInput2.addEventListener('keyup', function () {
        **while (rtextDiv.firstChild) {**
            rtextDiv.removeChild(rtextDiv.firstChild);
        }
        rtextDiv.appendChild(filterTable(refilterInput2.value, fil1));
    });
}
Eugene Mihaylin
  • 1,736
  • 3
  • 16
  • 31
Francesco
  • 69
  • 3
  • 10
  • ok,but why undifined?!it defined globally,to these functions,isn't it? – Francesco Dec 05 '14 at 13:52
  • this error comes when the first eventListener is done and rtextDiv has some value,and i take an action on the second listener,that it makes sense,now it should has some values in it,am i wrong?! – Francesco Dec 05 '14 at 13:57
  • That's because the events handle wrong elements. See [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – JJJ Dec 05 '14 at 13:58
  • tnx,anyway i don't understand whats happend to my code! if the rtextDiv = ... is the source of this problem(for knowing it as a local var)how can i use global vars?! – Francesco Dec 05 '14 at 14:07
  • It's not the source of the problem. The problem is the closure. – JJJ Dec 05 '14 at 14:19

0 Answers0