1

我正在尝试截断 div 标头。我相信,我的功能是有问题的,因为范围可变。

这是我的功能分解:

  1. 设置变量,使它们的范围正确
  2. 循环遍历每个 div:
    • 保存长标题
    • 创建截断的标题
    • 设置截断的标题
  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);
    });

}
4

1 回答 1

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

});
于 2012-10-18T11:25:07.193 回答