A jquery array returning one undefined?

I am trying to get an array from this html code to add fields having numbers in my id to my content:

<a href="#" data-box="38,39,40">An Array</a> 

Boxes for adding:

 <div id="box38"> ... </div> <div id="box39"> ... </div> <div id="box40"> ... </div> 

Since there are also html lines such as:

 <a href="#" data-box="24">No Array</a> 

I also need something that detects if there are multiple values ​​or only one. In this case, I just used if (theid.length > 2) , because single values ​​will not be more than two characters.

The array must be [38,39,49] , and it is, since console.log(theid); returns exactly this array.

 var theid = $(this).data('box'); var newHTML = ''; if (theid.length > 2) { theid = theid.split(','); $.each(theid, function(idx) { newHTML += $('#box' + theid[idx]).html(); }); } else { var newHTML = ''; newHTML = $('#box' + theid).html(); console.log(theid); }; 

But if I add newHTML to my existing content content.html(newHTML); Are there always "undefined" before the loaded fields? Here is a screenshot:

enter image description here

+6
source share
1 answer

This is a byproduct of variable lift. Since you use the += operator, the line is added to the end of the newHTML variable, which previously contained undefined. You can look at it like this:

 //hoisted var newHTML = undefined; var theid = $(this).data('box'); if (theid.length > 2) { theid = theid.split(','); $.each(theid, function(idx) { newHTML += $('#box' + theid[idx]).html(); }); } else { /*var */newHTML = ''; newHTML = $('#box' + theid).html(); console.log(theid); }; 
+3
source

Source: https://habr.com/ru/post/971329/


All Articles