gpt4 book ai didi

javascript - TypeScript (JS) - 从 onchange 函数获取更改的值

转载 作者:行者123 更新时间:2023-12-02 16:03:23 28 4
gpt4 key购买 nike

我想做的是在 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);
}

最佳答案

您不能使用 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);
};

关于javascript - TypeScript (JS) - 从 onchange 函数获取更改的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30981291/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com