2012-10-18 58 views
1

我想截断div头。我的功能是错误的,因为,我相信,可变范围。使用.each()的功能跨越变量

这里是我的功能细分:

  1. 设置变量,使他们通过各自的div正常范围的
  2. 循环:
    • 保存长标题
    • 创建截断标题
    • 设置截断标题
  3. 在鼠标输入,使用全称
  4. 当鼠标离开,用截断标题

我怎样才能重新安排该功能使变量在正确执行?

jQuery(document).ready(function($) { 
    eventHover(); 
}); 


function eventHover(){ 

    // Set var scope 
    var title = ''; 
    var shortText = ''; 
    var longText = ''; 

    // Change long titles to short version 
    $('#event_promo .panel').each(function() { 
     title = $(this).find($('h3 a')); 
     longText = title.html(); 

     shortText = jQuery.trim(longText).substring(0, 50) 
      .split(" ").slice(0, -1).join(" ") + "..."; 

     title.html(shortText); 
    }); 

    // Add hover class and change title to long version 
    $('#event_promo .panel .trigger').mouseenter(function() { 
     $(this).parent().addClass('hover'); 
     title.html(longText); 
    }); 

    // Remove hover class and revert title to short version 
    $('#event_promo .panel .trigger').mouseleave(function() { 
     $(this).parent().removeClass('hover'); 
     title.html(shortText); 
    }); 

} 

回答

2

我会建议使用data()法在 “全局” 变量:

$('#event_promo .panel').each(function() { 

    var $title = $(this).find('h3 a'); 
    var longText = title.html(); 

    var shortText = jQuery.trim(longText).substring(0, 50) 
     .split(" ").slice(0, -1).join(" ") + "..."; 

    $title.html(shortText); 

    $(this).data({ shortText: shortText, longText: longText }); 
}); 

处理数据:

$('#event_promo .panel .trigger').mouseenter(function() { 

    var longText = $(this).closest('.panel').data('longText'); 
    var shortText = $(this).closest('.panel').data('shortText'); 

    //do stuff with the texts here 

}); 
+0

我甚至不知道数据()函数存在,非常有帮助,谢谢! – theorise

+0

@theorise Np!作为一个方面说明:它也适用于html5数据。在这种情况下,数据存储在缓存对象中。 – Johan

+0

哦,那真是太棒了,再次感谢! – theorise