Javascript / jQuery函数产生未定义的

时间:2010-11-16 13:07:32

标签: javascript jquery

不久前我在这里问了一个问题,关于如何计算当标题长于给定容器中的一行时,然后将这些行中的每一行包裹在<span>中:

Use Javascript/jQuery to determine where a heading breaks to the next line?

我选择了一个对我有用的答案,至少在我检查IE7和IE6之前,其中所有由此脚本处理的标题呈现为

“的 undefinedundefinedundefinedundefinedundefinedundefined [...]”

在页面上

。由于我不是一个真正的JavaScript人(这就是我首先提出这样一个问题的原因),因此我很难找出问题所在。我假设一个未定义的变量或其他东西,但我似乎无法掌握它。

有人可以帮忙吗?

我将在此重复此代码,但请参阅上面的链接以获取上下文:

$(function(){
  $h = $('.fixed').find('h3');
  $h.each(function(i,e){
    var txt = $(e).text();
    $th = $('<h3 />').prependTo($(e).parent());
    var lh = $(e).text('X').height();
    $(e).text('');
    while (txt.length > 0) {
        $th.text($th.text() + txt[0]);
        txt = txt.slice(1);
        if (($th.height() > lh) || (txt.length <= 0)) {
            var shc = $th.text().split(' ');
            var ph = shc.slice(0,-1).join(' ')+' ';
            if (txt.length <= 0) { ph += shc.pop(); }
            $('<span />').text(ph).appendTo($(e));
            $th.text(shc.pop());
        }
    }
    $th.remove();
  })
});

2 个答案:

答案 0 :(得分:2)

您需要更改

$th.text($th.text() + txt[0]);

$th.text($th.text() + txt.charAt(0));

IE&lt; 8不接受通过数组索引的字符串位置;)

样式不起作用,但这将是一个CSS问题,我离开之前无法修复。但是所有东西都被包裹在一起:)

答案 1 :(得分:0)

没有什么事情发生在我身上。但是,既然你在评论中提到你在Firebug中看到“未定义”,我会从那里开始。即使这些浏览器优雅地失败,您看到未定义的事实是您第一次提示为难以诊断的IE6 / 7找到问题。我会在函数中使用Firebug和断点,或使用一些console.log()调用来记录您正在使用的值是每个步骤。一旦你开始看到未定义......你可能已经找到了你的问题。