问题
I have a set of check boxes with Id's user1,user2 and so on and also set of combo boxes with Id's usersel1,usersel2 and so on in a dialog. When a check box is checked (say suppose with Id user1) then corresponding combo box must be activated(i.e combo box with Id usersel1). I have the following code and isn't working. How do i achieve this behavior?
for(var g=0;g<userlist.length;g++) //userlist.length give no of users
b2 = (goog.dom.getElement('usersel'+(g+1))); //gets combo box
//listening if check box is clicked
goog.events.listen(goog.dom.getElement('user'+(g+1)),
goog.events.EventType.CLICK,
function(e) {
b2.disabled = (false); // trying to enable corresponding combo box
});
The problem with above piece of code is that any check box is clicked only the last combo box gets activated.
回答1:
There are couple of issues.
First, the for
cycle is applied only to the second line, not to the whole block.
Second, the way of creating the closure is wrong (see here). The value b2 is not propagated into the event handlers as you would think.
It would work if rewritten like this:
for (var g=0;g<userlist.length;g++) { //userlist.length give no of users
b2 = goog.dom.getElement('usersel'+(g+1)); //gets combo box
//listening if check box is clicked
goog.events.listen(goog.dom.getElement('user'+(g+1)),
goog.events.EventType.CLICK,
makeEventHandler(b2)
);
}
function makeEventHandler(element) {
return function(e) {
element.disabled = false;
}
}
来源:https://stackoverflow.com/questions/18732891/activate-a-combobox-from-a-checkbox-using-google-closure