【问题标题】:Why do does my jquery variable return undefined in firebug console为什么我的 jquery 变量在 firebug 控制台中返回 undefined
【发布时间】:2014-07-17 03:14:59
【问题描述】:

这是我的代码:

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");

剧透,以摆脱“看起来您的帖子主要是代码;请添加更多详细信息。”

【问题讨论】:

  • 你能添加你的 HTML 吗?还是做一个 JSFiddle?
  • 为什么你的选择器是这样写的?它们应该是几个选择器还是一个?
  • 这里是 JS fiddel,我已经简化了 Html 和代码......希望有人能帮助检查为什么 var selAlt 被视为未定义 jsfiddle.net/A5rdV

标签: jquery arrays firebug undefined


【解决方案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');

【讨论】:

  • 感谢 Action Dan,我累了,但是当我使用 alt 时,jquery 仍然中断,Alt var 仍然被视为 undefined var alt = $a.attr('title'); var indexResult = alt.indexOf("Not");
  • @ARGO 包含开头的标题怎么样。 var $a = $('');
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-18
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
相关资源
最近更新 更多