我想要做的是在HTMLInputElement上触发onchange事件后获取新值。我知道我可以通过使用element.value来获得它,但是这不会在大局中起作用。请参阅以下代码:
//This Works:
elem.onchange = (ev: Event) => {
var newValue = (<HTMLInputElement>ev.srcElement).value;
alert("Old: " + this._data[key] + ", New: " + newValue);
}
//Is there anyway I can get it to work like below? Currently I keep getting old values as new and old.
elem.onchange = (ev: Event) => {
var attName = "checked"; //or "value" for example
var newValue = ev.srcElement.getAttribute(attName);
alert("Old: " + this._data[key] + ", New: " + newValue);
}
答案 0 :(得分:2)
您无法使用getAttribute("checked")
来判断是否选中了复选框。您需要使用checked
属性:
elem.onchange = function (ev) {
var element = <HTMLInputElement>ev.srcElement,
newValue: string | boolean;
if (element.type === "checkbox") {
newValue = element.checked;
}
else {
newValue = element.value;
}
alert("Old: " + this._data[key] + ", New: " + newValue);
};