我正在 forEach
循环中制作按钮,但是当我尝试为按钮的 onClick
标记提供一个函数时,它显示 this.foo()
不是一个函数。代码如下:
dojo.forEach(buttonIds, function(btn, i) {
var button = new dijit.form.Button({
id: buttonIds[i]+'.'+widgetId,
label: buttonLabel[i],
onClick: function () {
dojo.hitch(this, this.foo());}
});
现在也许 dojo.connect()
在这里更合适,但我不知道如何获取按钮 ID 作为第一个参数,因为如果我理解正确,那么 connect 看起来像 dojo.connect(button.id, 'onClick', this, foo())
。不幸的是,这个语句也会导致同样的错误。这可能是一个微不足道的范围问题,但我在道场上很新,所以任何帮助将不胜感激!
编辑:抱歉,dojo.connect()
错误是按钮未定义
最佳答案
dojo.forEach
实际上接受三个参数( source ):
The dojo.forEach method accepts three (3) arguments: an array to iterate over, a function (or callback) to call for each item of the array (including unassigned indexes between assigned ones, as described above), and an optional object to use as the scope in which to call the callback.
你的dojo.hitch
中的this
指向回调函数,添加this
作为第三个参数:
dojo.forEach(buttonIds, function(item, index, items) { /*callback*/ }, this);
// or alternatively
var self = this;
dojo.forEach(buttonIds, function(item, index, items) { /*use self instead of this here*/ });
我不确定你要实现什么,但这是我的猜测:
dojo.require("dijit.form.Button");
dojo.ready(function() {
dojo.declare("Spam", null, {
constructor: function() {
this.buttonIds = ["button1", "button2", "button3"];
},
createButtons: function() {
dojo.forEach(this.buttonIds, function(item, index, items) {
var button = new dijit.form.Button({
id: item,
label: item
});
button.onClick = dojo.hitch(this, "foo", button);
button.placeAt(dojo.body());
}, this);
},
foo: function(widget, event) {
console.log(widget.id);
}
});
var spam = new Spam();
spam.createButtons();
});
在 jsFiddle 上查看它的实际情况:http://jsfiddle.net/phusick/mcnjt/
关于javascript - onClick 标签内的函数超出 dojo 1.6 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12480947/