问题描述
我使用Prototype来监控复选框,因此我可以向他们添加javascript检查。当单击复选框所在的tr或td时,应选中复选框。
当直接单击复选框时,onchange事件将触发,因此您将收到警报。当复选框的值被javascript改变时(当你点击tr或td),onchange不会被触发。为什么当复选框间接改变时,onchange不会触发?
I'm using Prototype to monitor checkboxes, so I can add javascript checks to them. When the tr or td in which the checkbox is located is clicked, the checkbox should be checked.
When you click directly on a checkbox, the onchange event is fired, so you'll get an alert. When the checkbox' value is changed by javascript (when you click on the tr or td), onchange is not fired. Why is onchange not fired when the checkbox is changed indirectly?
这是我正在使用的JavaScript。
This is the javascript I'm using.
Element.observe(window, 'load', function() {
/* If a tr or td is clicked, change the value of the checkbox. */
$$('#results tr').each(function(el) {
el.observe('click', function(e) {
if(!e.target) { e.target = e.srcElement; }
if(e.target.nodeName == 'TD' || e.target.nodeName == 'TR') {
$('compare-product'+this.id).checked = ($('compare-product'+this.id).checked === false) ? true : false;
}
});
});
/* Monitor if the status of a checkbox has changed. */
$$('#results tr td input').each(function(el) {
el.observe('change', function(e) {
alert('!');
}
);
}
);
}
);
我在Firefox和IE7中测试过,两者都不工作。我不想寻找解决方法,我只是想知道为什么这不工作。
I've tested it in Firefox and IE7, both are not working. I'm not looking for a workaround, I'm just curious to know why this doesn't work.
推荐答案
This isn在UI框架中一般不常见。如果你以编程方式改变控件的状态,我们假设你也能够以编程方式触发它应该有的副作用。它给程序员更大的灵活性,它避免了在初始化或拆卸期间状态不稳定的错误。 (例如,在初始化期间,您可以在设置多个依赖的控件的状态之前设置一个控件的状态。如果第一个控件的更改处理程序立即激活,则会执行,而其他控件处于不一致状态。)
This isn't uncommon in UI frameworks in general. If you change the state of a control programmatically, it's assumed that you're also capable of programmatically triggering whatever side-effects it's supposed to have. It gives programmers more flexibility, and it avoids bugs where the state is in flux during initialization or teardown. (For example, during initialization, you might set the state of one control before setting the state of several dependent ones. If the change handler for the first control fires immediately, it will execute while the other controls are in an inconsistent state.)
这篇关于为什么当复选框间接更改时,复选框上的onchange不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!