0

我有以下功能:

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。为什么onchange第 4 行里面的函数没有使用我之前定义的变量?我将如何正确重写上述内容?

4

3 回答 3

2

你是这个意思吗?

$(this).html("<select id='sel' onchange='selectdone(this, "+title_id+");'>...</select>");
于 2012-06-26T22:51:07.283 回答
0

在这里使用字符串连接:

$(this).html("<select id='sel' onchange='selectdone(this, title_id=" + title_id +");'>...
于 2012-06-26T22:51:37.177 回答
0

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

试试这个:

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

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

于 2012-06-26T22:51:48.860 回答