我有这样的代码:
<input type="text" id="point-setter-input" onkeyup="if (!isNaN(this.value)) {document.getElementById('point-setter-span').setAttribute('data-data', 'data=' + this.value)};" onpaste="if (!isNaN(this.value)) {document.getElementById('point-setter-span').setAttribute('data-data', 'data=' + this.value)};" value="0">
<span class="api command initialized" data-command-name="SetPoints" data-events="click" data-container="#popup-content" id="point-setter-span" data-data="data=3">Pontok Mentése</span>每当value的input通过onkeyup进行更改时,如果它恰好是一个数字,那么span的data-data就会得到这个值。然而,onpaste永远不会运行。如果我通过键盘粘贴,那么data-data的span将被成功地更新,但这只是因为我的onkeyup,也就是说,如果我没有这个属性,即使粘贴到键盘也不会运行。为什么onpaste在我的情况下不正常?我在Chrome和Firefox中查过这个。
编辑
原来onpaste是执行的,但值不是粘贴的文本。我认为这里需要一个丑陋的解决方案,涉及到setTimeout。
发布于 2018-05-24 10:29:07
粘贴事件在设置<input>值之前触发,否则无法阻止其默认行为(即设置<input>值)。
因此,当您检查if(!isNaN(this.value))时,仍然没有设置粘贴事件中包含的新值。
要解决这个问题,只需听一听输入事件,在任何情况下都会被触发。
var inp = document.getElementById('inp');
inp.onpaste = function() {
console.log('paste', this.value);
};
inp.oninput = function() {
console.log('input', this.value);
}<input type="text" id="inp">
发布于 2018-05-24 10:35:49
我已经使用setTimeout解决了这个问题,所以当我使用它时,值被更改了:
<input type="text" id="point-setter-input" onkeyup="setTimeout(() => {if (!isNaN(this.value.trim())) {document.getElementById('point-setter-span').setAttribute('data-data', 'data=' + this.value)};}, 4);" onpaste="setTimeout(() => {if (!isNaN(this.value.trim())) {document.getElementById('point-setter-span').setAttribute('data-data', 'data=' + this.value)};}, 4);" value="0">https://stackoverflow.com/questions/50506530
复制相似问题