简体   繁体   中英

Iterating arrays events & listeners javascript

I am trying to iterate a simple array using event and listeners , but when I try to see the content on html with property inner I receive a large sequence of numbers ... I think I don't know how to render this information.

The HTML

<body onload="exampleFunctions()">
    <div id="cargarMenu"><ul>
  <li><a href="spain.html">España</a></li>
  <li><a href="france.html">Francia</a></li>
  <li><a href="countries.html">Países por region</a></li>
</ul>
</div>
    <div id="cargarInfo"><div id="nombre"></div>
<div id="capital"></div></div>
    <div id="wrapper">FOO! 012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152</div>

My Listener has the following content

<script>
var wrapper = document.getElementById('wrapper');
 window.addEventListener("infoCountries",function(e){
    totalnames = e.detail.totalNames;
    for(var i=0;i<totalnames;i++){
         wrapper.innerHTML +=i;
    };
  })
</script>
</body>

And my event , I think is correctly created

$(document).ready(function() {
    $.ajax({
        url: "https://restcountries.eu/rest/v2/region/europe"
    }).then(function(data) {
        var names = new Array();
        var capital= new Array();
        var borders = new Array();
        var subregion = new Array();
        for(var i=0;i<data.length;i++){ 
            names.push(data[i].name);
            capital.push(data[i].capital);
            for(var j=0;j<data[i].borders.length;j++){
                borders.push(data[i].borders[j]);   
            }
            subregion.push(data[i].subregion);  
        }
        var evt = new CustomEvent("infoCountries",{
          detail:{
                nm:names,
                totalNames:names.length,
                capital: capitales,
                borders: borders,
                subregion:subregion
            }
        });
        window.dispatchEvent(evt);
    });
});

Could anyone help to me?

You're just concatenating the numbers from 0 to totalNames-1 , you're not doing anything with the names array. It should be:

 window.addEventListener("infoCountries",function(e){
    var totalnames = e.detail.totalNames;
    var names = e.detail.nm;
    for(var i=0;i<totalnames;i++){
         wrapper.innerHTML += names[i] + " ";
    };
  })

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