Can I pass parameter from a dynamic created dijit button onClick?

我们两清 提交于 2019-12-10 15:25:50

问题


I wonder, can I pass parameter from a dynamic created dijit button ?

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 ) ;

Seems , this dosen't work, I tried to change to this. It works !!

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 ) ;

The question is , I want to let the function know, which button has been clicked (as all buttons are dynamically created, and the button id is generate by indexnumber), so I need to pass the button itself's id to the function. But passing parameter through onClick call seems not work in Dijit . How can I make it work ?


回答1:


No worries, this is a very common Javascript mistake - in fact, it has nothing to do with Dojo.

onClick expects a function object, but you are actually executing testcallfromDynamicButton('test') and assigning the result from this function call to it. For example, if testcallfromDynamicButton returned "colacat", the onClick event would be given that string! That's obviously not what you want.

So we need to make sure onClick is given a function object, like you do in your second example. But we also want to give that function an argument when it's executed. The way to do this is to wrap your function call in an anonymous function, like so:

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

This way, onClick gets a function object, and testcallfromDynamicButton is executed with an argument.



来源:https://stackoverflow.com/questions/6092434/can-i-pass-parameter-from-a-dynamic-created-dijit-button-onclick

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!