nayakasu
nayakasu

Reputation: 969

JavaScript global array undefined although it shows in alert

I have written a JQuery script in SharePoint to truncate a multiple lines of text column. Below is the script:

<script>

 window.$divs = [];
 window.$i = 0;
 window.textFull = new Array();

 $(document).ready(function(){
 window.setInterval(function(){
  /// call your function here
 $divs = $("[class^=ExternalClass]");
 for($i=0;$i<$divs.length;$i++)
 {
  textFull[$i] = $($divs[$i]).html();
  if(typeof textFull[$i] != 'undefined' && textFull[$i].length > 50)
  {
   //alert($textFull[$i]); this alert show the correct text
   $($divs[$i]).html(textFull[$i].substring(0,49)+"<a href='javascript:alert(textFull[$i]);'>...more</a>");
  }
 }
}, 500);


 });

 </script>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

In the above code "javascript:alert(textFull[$i])" shows 'undefined' in alert. But the alert above it shows correct text. Also I when I use a variable instead of an array it works fine in the alert inside anchor tag. I have also declared the array as global. So what am I missing?

Upvotes: 1

Views: 491

Answers (1)

charlietfl
charlietfl

Reputation: 171669

You are running into the classic problem using for loop without using a closure to keep track of the index with

No need to create that array if all it is used for is to modify the html

Can do that much simpler using html(fn) and a jQuery event handler

$("[class^=ExternalClass]").html(function(index, oldhtml){
   if(oldhtml.length >=50){
       // store the full html in element data
       $(this).data('html', oldhtml)
       return oldhtml.substring(0,49)+"<a class="more-btn">...more</a>"
   } else{
       return oldhtml
   }
}).find('.more-btn').click(function(){
     var $div =  $(this).parent();
     $div.html( $div.data('html'));    
});

Upvotes: 1

Related Questions