内联 JavaScript 未捕获的引用错误

Uncaught Reference Error with inline javascript

本文关键字:引用 错误 JavaScript 内联      更新时间:2023-09-26

我有以下函数:

if ($(this).find('#sel').length == 0) {
    var before = $(this).text();
    var title_id = $(this).parent().attr('id');
    $(this).html("<select id='sel' onchange='selectdone(this, title_id=title_id)>
                   ...</select>");
}

由此我得到Uncaught ReferenceError: title_id is not defined.为什么第 4 行内部的 onchange 函数没有拾取我之前定义的变量?我将如何正确重写上述内容?

你是这个意思吗?

$(this).html("<select id='sel' onchange='selectdone(this, "+title_id+");'>...</select>");

在此处使用字符串连接:

$(this).html("<select id='sel' onchange='selectdone(this, title_id=" + title_id +");'>...

发生这种情况是因为您将"change"处理程序定义为字符串的一部分,因此语言不知道其中有代码。

试试这个:

$(this).html($("<select/>", {
  id: 'sel',
  change: function() { selectdone(this, title_id) }
}));

由于你无论如何都在使用 jQuery,你应该养成通过库而不是使用"onfoo"属性来管理事件处理程序的习惯。