Pav*_*vel 3 javascript javascript-events
所以我正在尝试使用javascript进行自定义标签系统.但是,为了重用我想用OOP风格编写的代码.这就是我到目前为止:
function Tabs()
{
this.tabArray = new Array(arguments.length);
this.tabArrayC = new Array(arguments.length);
for(i=0;i<arguments.length;i++)
{
this.tabArray[i] = arguments[i];
this.tabArrayC[i] = arguments[i]+'_content';
}
this.setClickable = setClickable;
function setClickable()
{
for(i=0;i<this.tabArray.length;i++)
{
document.getElementById(this.tabArray[i]).onclick = function()
{
alert(this.tabArray[i]);
}
}
}
}
function init()
{
tab = new Tabs('tab1','tab2','tab3','tab4');
tab.setClickable();
}
window.onload = init();
Run Code Online (Sandbox Code Playgroud)
现在这是交易.我想将onclick事件处理程序分配给在Tabs'类'构造函数中传递的每个选项卡.所以稍后在代码中我写了类似的东西:
<div id="tab1">Tab1</div>
<div id="tab2">Tab2</div>
<div id="tab3">Tab3</div>
<div id="tab4">Tab4</div>
Run Code Online (Sandbox Code Playgroud)
之前设置的代码:
document.getElementById(this.tabArray[i]).onclick = function()
{
alert(this.tabArray[i]);
}
Run Code Online (Sandbox Code Playgroud)
......将被执行.我希望我解释得那么好.有任何想法吗?
您的setClickable功能有三个问题(编辑:以及您如何调用的问题init):
this将在您生成的事件处理程序中具有与您期望的不同的含义.(更多信息:你必须记住this)
闭包(一个关闭数据的函数,如i变量)具有对变量的持久引用,而不是其值的副本.因此,所有处理程序将i在运行时看到,而不是在它们何时创建时.(更多信息:闭包并不复杂)
你没有宣布i,所以你正在成为隐形全球恐怖的牺牲品.
以下是解决这些问题的一种方法:
function setClickable()
{
var i; // <== Declare `i`
var self = this; // <== Create a local variable for the `this` value
for(i=0;i<this.tabArray.length;i++)
{
// v=== Use a function to construct the handler
document.getElementById(this.tabArray[i]).onclick = createHandler(i);
}
function createHandler(index)
{
// This uses `self` from the outer function, which is the
// value `this` had, and `index` from the call to this
// function. The handler we're returning will always use
// the `index` that was passed into `createHandler` on the
// call that created the handler, so it's not going to change.
return function() {
alert(self.tabArray[index]);
};
}
}
Run Code Online (Sandbox Code Playgroud)
...并作为goreSplatter和Felix指出,此行:
window.onload = init();
Run Code Online (Sandbox Code Playgroud)
... 调用的init功能,并使用它的返回值分配给onload.你的意思是:
window.onload = init;
Run Code Online (Sandbox Code Playgroud)
......只是分配init给onload活动.
偏离主题:您可以考虑使用较新的"DOM2"机制来附加事件处理程序,而不是使用onXYZ属性和属性的旧"DOM0"方式.这种新方式被称为addEventListener,尽管可悲的是Internet Explorer最近才添加了这种方式(但它具有attachEvent非常相似的特性).如果您使用jQuery,Prototype,YUI,Closure或其他任何库中的库,它们将为您消除这些差异(并提供许多其他有用的东西).
| 归档时间: |
|
| 查看次数: |
1046 次 |
| 最近记录: |