在 OnKeyUp 事件问题中引用 Javascript 变量
我声明了两个变量,COURSE_ID_List 和 COURSE_ID_timerId。然后它们作为参数从 OnKeyUp 事件传递给 SetFilter 函数。
如果列表未定义,则应对其进行初始化。问题是该列表始终是未定义的,因此我假设 OnKeyUp 事件中使用的 COURSE_ID_List 是按值而不是按引用传递的。我该如何解决这个问题?
谢谢
<script type="text/javascript">
function SetFilter(ddl, value, list, timerId) {
if (list == undefined)
list = new ListFilter(ddl);
clearTimeout(timerId);
timerId = setTimeout(function() { list.SetFilter(value);}, 1500);
}
var COURSE_ID_List;
var COURSE_ID_List_timerId;
</script>
<input name="Course" type="text" id="COURSE_ID" onKeyUp="SetFilter('COURSE_ID', this.value, COURSE_ID_List, COURSE_ID_List_timerId);" />
I've declared two variables, COURSE_ID_List and COURSE_ID_timerId. They then get passed as parameters to the SetFilter function from the OnKeyUp event.
If the list is undefined, it should initialise it. The problem is that the list is always undefined, so I assume the COURSE_ID_List used in the OnKeyUp event is being passed in by value and not by reference. How can I get around this?
Thanks
<script type="text/javascript">
function SetFilter(ddl, value, list, timerId) {
if (list == undefined)
list = new ListFilter(ddl);
clearTimeout(timerId);
timerId = setTimeout(function() { list.SetFilter(value);}, 1500);
}
var COURSE_ID_List;
var COURSE_ID_List_timerId;
</script>
<input name="Course" type="text" id="COURSE_ID" onKeyUp="SetFilter('COURSE_ID', this.value, COURSE_ID_List, COURSE_ID_List_timerId);" />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 JavaScript 中通过引用传递是很尴尬的。对象仅具有通过引用传递的值,因此重新分配给变量名会导致该变量名具有新值,但原始变量保留其值。
我打算向 Yves M,但我从你的评论中看到你已经尝试过。另一种解决方案是使用对象并操纵它们的属性。我认为您想要实现的目标如下所示,
另外,我想重申我关于选择输入处理的替代事件的评论。 oninput (HTML5) 和onpropertychange (Internet Explorer) 在捕获文本输入方面做得更好。
Pass by reference is awkward in JavaScript. Objects have only their value passed by reference, so re-assigning to a variable name results in that variable name having a new value, but the original variable retains its value.
I was going to post a similar solution to Yves M, but I see from your comments that you already tried that. The other solution is to use objects and manipulate their properties instead. Something like the following is what I think you're trying to achieve,
Also, I'd like to re-iterate my comment about choosing an alternative event for input handling. oninput (HTML5) and onpropertychange (Internet Explorer) do a much better job of catching text input.
更改为...
并且
更通用的方法将使用原型制作...
Change to...
and
A more generic approach would use prototyping...
我想这可能就是您正在寻找的答案。
和
I think this may be the answer you are looking for.
and