[英]Uncaught Reference Error with inline javascript
I have the following function: 我有以下功能:
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>");
}
From this I get Uncaught ReferenceError: title_id is not defined
. 从这里我得到
Uncaught ReferenceError: title_id is not defined
。 Why isn't the onchange
function inside on line 4 not picking up on the variable that I've defined previously? 为什么第4行的
onchange
函数没有接收到我之前定义的变量? How would I rewrite the above correctly? 我该如何正确地重写上述内容?
你的意思是?
$(this).html("<select id='sel' onchange='selectdone(this, "+title_id+");'>...</select>");
在这里使用字符串连接:
$(this).html("<select id='sel' onchange='selectdone(this, title_id=" + title_id +");'>...
It's happening because you're defining the "change" handler as part of a string, so the language has no idea that there's code in there. 它正在发生,因为你将“更改”处理程序定义为字符串的一部分,因此语言不知道那里有代码。
Try this: 尝试这个:
$(this).html($("<select/>", {
id: 'sel',
change: function() { selectdone(this, title_id) }
}));
Since you're using jQuery anyway, you should get in the habit of managing your event handlers via the library instead of with "onfoo" attributes. 既然你正在使用jQuery,你应该养成通过库而不是“onfoo”属性管理事件处理程序的习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.