为什么我的jquery变量在firebug控制台中返回undefined

时间:2014-07-16 08:42:44

标签: jquery arrays firebug undefined

这是我的代码:

var altArr = [];
i = 0;
$('ul.ctopics.topics img').each(function () {
    altArr[i++] = $(this).attr('alt')
});

var linkArr = [];
c = 0;
$('ul.ctopics.topics .activityinstance a').each(function () {
    linkArr[c++] = $(this).attr('href')
});

a = 0;
var scormId = [];
$('ul.ctopics.topics li.modtype_scorm').each(function () {
    scormId[a++] = $(this).attr('id')
});

b = 0;
var idArr = [];

$('.course-matrix .course-matrix-table tr').addClass('locked');

$('.course-matrix .course-matrix-table tr').each(function () {
    idArr[b++] = $(this).attr('id');
    idTr = $(this).attr('id');
    var matchArr = $.inArray(idTr, scormId);
    var selLink = linkArr[matchArr];
    var selAlt = altArr[matchArr];

    $(this).find('td.course-title').wrapInner('<a href="' + selLink + '" class="scorm-link"></a>');
    $(this).find('a.scorm-link').attr('title', selAlt);

    var alt = $(this).find('a.scorm-link').attr('title');
    var indexResult = alt.search("Not");

    if (indexResult >= 0) {
        $(this).removeClass('locked');
        $(this).addClass('not-yet-complete');
        $(this).addClass('unlocked');
    } else {
        $(this).addClass('completed');
        $(this).addClass('unlocked');
        $(this).removeClass('locked');
    }
});

我无法找到为什么我从Firebug收到此错误。这打破了我后续的JS代码:

TypeError: alt is undefined
var indexResult = alt.search("Not");
  扰乱摆脱&#34;看起来你的帖子主要是代码;请添加更多细节。&#34;

1 个答案:

答案 0 :(得分:1)

您正在动态添加DOM元素,然后搜索它们。但是当您添加它们时,您可以分配给变量。比如这个(未经测试)但你明白了:

替换它:

$(this).find('td.course-title').wrapInner('<a href="'+selLink+'" class="scorm-link" title=""></a>');
$(this).find('a.scorm-link').attr('title', selAlt);

var alt = $(this).find('a.scorm-link').attr('title');

有这样的事情:

//first create your nodes, and remember them as variables. Use the $ prefix so you know it is a jquery object that is stored in the variable
var $td = $(this).find('td.course-title');
var $a = $('<a href="'+selLink+'" class="scorm-link"></a>');

//add the link to the cell
$td.append($a);

//then set your attribute. Note you already have the variable so no need to search
$a.attr('title', selAlt)

//if you need you can then extract that title attribute
var alt = $a.attr('title');