我可以从动态创建的dijit按钮onClick传递参数吗?

Col*_*cat 4 dojo

我想知道,我可以从动态创建的dijit按钮传递参数吗?

function testcallfromDynamicButton (value) {
   alert(value);
}

var thisButton = new dijit.form.Button({
label : thelineindex ,
id : "I_del_butt"+thelineindex,
name : "I_del_butt"+thelineindex,
onClick : testcallfromDynamicButton('test')
}).placeAt( thetabletd1 ) ;
Run Code Online (Sandbox Code Playgroud)

好像,这不行,我试着改变这个.有用 !!

function testcallfromDynamicButton () {
alert('test');
}

var thisButton = new dijit.form.Button({
  label : thelineindex ,
  id : "I_del_butt"+thelineindex,
  name : "I_del_butt"+thelineindex,
  onClick : testcallfromDynamicButton
}).placeAt( thetabletd1 ) ;
Run Code Online (Sandbox Code Playgroud)

现在的问题是,我想让功能都知道,已经被点击了哪个按钮(如所有按钮是动态创建的,并且按钮的id是indexnumber产生),所以我需要按钮本身的ID传递给函数.但是通过onClick调用传递参数似乎在Dijit中不起作用.我怎样才能使它工作?

Fro*_*ode 8

不用担心,这是一个非常常见的Javascript错误 - 事实上,它与Dojo无关.

onClick需要一个函数对象,但实际上是在执行testcallfromDynamicButton('test')并将此函数调用的结果赋给它.例如,如果testcallfromDynamicButton返回"colacat",onClick事件将被赋予该字符串!那显然不是你想要的.

所以我们需要确保onClick给出一个函数对象,就像在第二个例子中那样.但是我们也希望在执行时给该函数一个参数.这样做的方法是将函数调用包装在匿名函数中,如下所示:

var thisButton = new dijit.form.Button({
  label : thelineindex ,
  id : "I_del_butt"+thelineindex,
  name : "I_del_butt"+thelineindex,
  onClick : function() {
    testcallfromDynamicButton('test');
  }
}).placeAt( thetabletd1 ) ;
Run Code Online (Sandbox Code Playgroud)

这样,onClick获取一个函数对象,并testcallfromDynamicButton使用参数执行.